I am new to C# and was wondering how to get a file by the name the user puts into a text box, then load that data into an array and display each item in the array into separate text boxes to then be edited and saved to that file again
namespace test
{
public partial class Form1 : Form
{
private TextBox[] textBoxes;
private Button[] buttons;
private const string fileName = (getFile.Text);
public Form1()
{
InitializeComponent();
textBoxes = new TextBox[] { textBox1, textBox2, textBox3, textBox4 };
buttons = new Button[] { button1, button2, button3, button4 };
}
private static void ReplaceLineInFile(string path, int lineNumber, string newLine)
{
if (File.Exists(path))
{
string[] lines = File.ReadAllLines(path);
lines[lineNumber] = newLine;
File.WriteAllLines(path, lines);
}
}
private void Form1_Load(object sender, EventArgs e)
{
LoadFile();
}
private void LoadFile()
{
if (!File.Exists(fileName))
{
WriteAllLines();
return;
}
string[] lines = File.ReadAllLines(fileName);
if (lines.Length != textBoxes.Length)
{
// the number of lines in the file doesn't fit so create a new file
WriteAllLines();
return;
}
for (int i = 0; i < lines.Length; i++)
{
textBoxes[i].Text = lines[i];
}
}
private void WriteAllLines()
{
// this will create the file or overwrite an existing one
File.WriteAllLines(fileName, textBoxes.Select(tb => tb.Text));
}
private void button1_Click(object sender, EventArgs e) // save line 1
{
ReplaceLineInFile(fileName, 0, textBox1.Text);
}
private void button2_Click(object sender, EventArgs e) // save line 2
{
ReplaceLineInFile(fileName, 1, textBox2.Text);
}
private void button3_Click_1(object sender, EventArgs e) // save line 3
{
ReplaceLineInFile(fileName, 2, textBox3.Text);
}
private void button4_Click(object sender, EventArgs e) // save line 4
{
ReplaceLineInFile(fileName, 3, textBox4.Text);
}
private void button_Click(object sender, EventArgs e) // save all
{
Button button = sender as Button;
if (button != null)
{
int lineNumber = Array.IndexOf(buttons, button);
if (lineNumber >= 0)
{
ReplaceLineInFile(fileName, lineNumber, textBoxes[lineNumber].Text);
}
}
}
private void button5_Click(object sender, EventArgs e) // get file
{
if (File.Exists(getFile.Text))
{
//shows message if testFile exist
MessageBox.Show("File " + getFile.Text + " Exist ");
}
else
{
//create the file testFile.txt
File.Create(getFile.Text);
MessageBox.Show("File " + getFile.Text + " created ");
}
}
}
}
First place a TableLayoutPanel control onto your form. This will help easily placing the other controls.
Dock this panel where you want, then Edit the columns and set the SizeType for both columns to AutoSize. Set AutoScroll to true. Leave the control with the default name tableLayoutPanel1.
Now change the methods. Remove all buttonX_Click methods and paste this code instead of the existing LoadFile:
private void button1_Click(object sender, EventArgs e)
{
string[] lines = File.ReadAllLines(fileName);
// Clear the existing rows
tableLayoutPanel1.RowStyles.Clear();
for (int i = 0; i < lines.Length; i++)
{
// Add a new row
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
// Create the TextBox
TextBox txt = new TextBox();
// Add any initializations for the text box here
txt.Text = lines[i];
// Create the button
Button btn = new Button();
// Add any initializations for the button here
btn.Text = i.ToString();
// Handle the button's click event
btn.Click += btn_Click;
// This value helps the button know where it is and which TextBox it is associated to
btn.Tag = new object[] { i, txt };
btn.Width = 30;
// Add the controls to the created row
tableLayoutPanel1.Controls.Add(txt, 0, i);
tableLayoutPanel1.Controls.Add(btn, 1, i);
}
}
void btn_Click(object sender, EventArgs e)
{
object[] btnData = (object[]) ((Control) sender).Tag;
// The values are inside the sender's Tag property
ReplaceLineInFile(fileName, (int)btnData[0], ((TextBox)btnData[1]).Text);
}
UPDATE: This is the whole source of the class, corrected:
namespace test
{
public partial class Form1 : Form
{
private string fileName;
public Form1()
{
InitializeComponent();
}
private void ReplaceLineInFile(int lineNumber, string newLine)
{
if (File.Exists(fileName))
{
string[] lines = File.ReadAllLines(fileName);
lines[lineNumber] = newLine;
File.WriteAllLines(fileName, lines);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void LoadFile()
{
string[] lines = File.ReadAllLines(fileName);
// Clear the existing rows
tableLayoutPanel1.RowStyles.Clear();
for (int i = 0; i < lines.Length; i++)
{
// Add a new row
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
// Create the TextBox
TextBox txt = new TextBox();
// Add any initializations for the text box here
txt.Text = lines[i];
// Create the button
Button btn = new Button();
// Add any initializations for the button here
btn.Text = i.ToString();
// Handle the button's click event
btn.Click += btn_Click;
// This value helps the button know where it is and which TextBox it is associated to
btn.Tag = new object[] { i, txt };
btn.Width = 30;
// Add the controls to the created row
tableLayoutPanel1.Controls.Add(txt, 0, i);
tableLayoutPanel1.Controls.Add(btn, 1, i);
}
}
void btn_Click(object sender, EventArgs e)
{
object[] btnData = (object[])((Control)sender).Tag;
// The values are inside the sender's Tag property
ReplaceLineInFile((int)btnData[0], ((TextBox)btnData[1]).Text);
}
private void button_Click(object sender, EventArgs e) // save all
{
List<string> lines = new List<string>();
for (int i = 0; i < tableLayoutPanel1.RowCount; i++)
{
lines.Add(((TextBox)tableLayoutPanel1.Controls[i * 2]).Text);
}
File.WriteAllLines(fileName, lines.ToArray());
}
private void button5_Click(object sender, EventArgs e) // get file
{
fileName = getFile.Text;
if (File.Exists(fileName))
{
//shows message if testFile exist
MessageBox.Show("File " + fileName + " Exist ");
}
else
{
//create the file testFile.txt
File.Create(fileName);
MessageBox.Show("File " + fileName + " created ");
}
LoadFile();
}
}
}
Related
I have problem with one function. Function "Usun" must delete both line in listbox and the same data from txt file** Can anyone help me?
using System;
namespace BazaKlientow2
{
public partial class Form1 : Form
{
private Klient[] lista = new Klient[1];
public Form1()
{
InitializeComponent();
}
private void Write(Klient obj)
{
StreamWriter sw = new StreamWriter("Klienci.txt");
sw.WriteLine(lista.Length + 1);
sw.WriteLine(obj.Imie);
sw.WriteLine(obj.Nazwisko);
sw.WriteLine(obj.Firma);
sw.WriteLine(obj.NIP);
for(int x = 0; x <lista.Length; x++)
{
sw.WriteLine(lista[x].Imie);
sw.WriteLine(lista[x].Nazwisko);
sw.WriteLine(lista[x].Firma);
sw.WriteLine(lista[x].NIP);
}
sw.Close();
}
private void Read()
{
StreamReader sr = new StreamReader("Klienci.txt");
lista = new Klient[Convert.ToInt32(sr.ReadLine())];
for (int x = 0; x < lista.Length; x++)
{
lista[x] = new Klient();
lista[x].Imie = sr.ReadLine();
lista[x].Nazwisko = sr.ReadLine();
lista[x].Firma = sr.ReadLine();
lista[x].NIP = sr.ReadLine();
}
sr.Close();
}
private void Display()
{
listaKlientow.Items.Clear();
for( int x=0; x < lista.Length; x++)
{
listaKlientow.Items.Add(lista[x].ToString());
}
}
private void ClearForm()
{
txtImie.Text = String.Empty;
txtNazwisko.Text = String.Empty;
txtFirma.Text = String.Empty;
txtNip.Text = String.Empty;
}
private void dodaj_Click(object sender, EventArgs e)
{
Klient obj = new Klient();
obj.Imie = txtImie.Text;
obj.Nazwisko = txtNazwisko.Text;
obj.Firma = txtFirma.Text;
obj.NIP = txtNip.Text;
Write(obj);
Read();
Display();
ClearForm();
}
private void Form1_Load(object sender, EventArgs e)
{
Read();
Display();
}
private void sortuj_Click(object sender, EventArgs e)
{
Sortowanie();
Display();
}
private void Sortowanie()
{
Klient temp;
bool swap;
do
{
swap = false;
for(int x=0;x<lista.Length -1;x++)
{
if(lista[x].Imie.CompareTo(lista[x+1].Nazwisko) >0)
{
temp = lista[x];
lista[x] = lista[x + 1];
lista[x + 1] = temp;
swap = true;
}
}
} while (swap == true);
}
private void usun_Click(object sender, EventArgs e)
{
Usun();
}
private void Usun()
{
**//i cant do this. this function must delete both line in listbox and the same data from txt file**
}
}
}
Function "Usun" must delete both line in listbox and the same data from txt file** Can anyone help me?
You need to read the lines from the file and store then in a List<string> memory. You also need to set the DataSource property of the ListBox to those lines. When you want to remove a line, remove it from the List<string> in memory. Then write the whole list back to the file. Then reset the DataSource property of the ListBox.
Here is an example. In this example, I create a file with "1", "2" and "3" as the lines. Then when the user clicks a button, I remove "1" from the list in memory and write the list to the file. Then I refresh the listbox.
public partial class Form1 : Form {
private List<string> linesInFile;
public Form1() {
InitializeComponent();
File.WriteAllLines( "Lines.txt", new string[] { "1", "2", "3" } );
this.linesInFile = File.ReadAllLines( "Lines.txt" ).ToList();
this.listBox1.DataSource = this.linesInFile;
}
private void Remove_Click(object sender, EventArgs e) {
this.linesInFile.Remove( "1" );
File.WriteAllLines( "Lines.txt", this.linesInFile );
this.listBox1.DataSource = null;
this.listBox1.DataSource = this.linesInFile;
}
}
I am developing an exe file
Which creates dynamic textboxes(no. of textboxes depends upon the user input in the one already provided textbox),
In the beginning it focus on the 1st textbox,
It should move focus to next textbox on click of "ENTER" key.
What I'm trying is:
private void Form1_Load(object sender, EventArgs e)
{
int a = 10;
for (int i = 1; i < 5; i++)
{
TextBox txtbx;
txtbx = new TextBox();
txtbx.Location = new Point(10, a);
a += 30;
this.Controls.Add(txtbx);
if(i==1)
{
txtbx.Focus();
}
}
}
public void Form1_KeyPessed(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ENTER)
{
SendKeys.Send("{TAB}");
}
}
Need to use Control.TabIndex Property and you need to bind key down event for each newly created Text box
Try this :
private void Form1_Load(object sender, EventArgs e)
{
int a = 10;
for (int i = 1; i < 5; i++)
{
TextBox txtbx;
txtbx = new TextBox();
txtbx.Location = new Point(10, a);
txtbx.KeyDown += Txtbx_KeyDown; //Added
txtbx.TabIndex = i; //Added
a += 30;
this.Controls.Add(txtbx);
if (i == 1)
{
txtbx.Focus();
}
}
}
Now add Key down handler
//Added
private void Txtbx_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode.Equals(Keys.Enter))
{
SendKeys.Send("{TAB}");
}
}
I have a scenario. following is the code:
Home.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
try
{
if (!String.IsNullOrEmpty(txtbox_query.Text.Trim()))
{
if (isTrue)
{
// To do statements
}
else
{
List<RequestAndResponse.Parameter> parameters = request.getParameter(txtbox_query.Text.Trim(), sourcePath, parameterValue);
Session["Data"] = parameters;
Response.Redirect("Result.aspx",false);
}
}
}
catch (Exception error)
{
Response.Write(error.Message);
}
}
Result.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
parameters = (List<RequestAndResponse.Parameter>)Session["Data"];
ContentPlaceHolder content = (ContentPlaceHolder)this.Form.FindControl("MainContent");
for (int j = 1; j <= _arrViewState; j++)
{
string _id = j.ToString();
TextBox txtfname = new TextBox();
txtfname.ID = "TextBox_" + _id + "_";
txtfname.Width = 160;
txtfname.Text = parameters[(j - 1)].Value.ToUpper();
txtfname.Attributes.Add("style", "color:#015D84;font-weight:bold;font-size:12px;padding:10px;");
txtfname.EnableViewState = true;
content.Controls.Add(txtfname);
content.Controls.Add(new LiteralControl("<br/>"));
}
Button btnSubmit = new Button();
btnSubmit.ID = "btnSubmit";
btnSubmit.Text = "Submit";
btnSubmit.Click += new System.EventHandler(btnSubmit_click);
btnSubmit.Enabled = false;
content.Controls.Add(btnSubmit);
}
protected void btnSubmit_click(object sender, EventArgs e)
{
// How to find the dynamically created textbox
}
Now How to find the dynamically created controls
I know the basic like:
Form.FindControl("TextBox ID");
But here i dont know the textbox id and also i even dont know how many textbox will be their as it totally depends on user input i.e. from 2 TO N textboxes
What i want is on bttn_Click i will fetch the text from all the textboxes
How will i achieve this.
Also i want to check if all Textbox is empty or not on bttn_Click
Enumerate controls as follows
protected void btnSubmit_click(object sender, EventArgs e)
{
ContentPlaceHolder content = (ContentPlaceHolder)this.Form.FindControl("MainContent");
foreach (Control c in content.Controls)
{
if (c is TextBox)
{
TextBox txt = (TextBox)c;
// do something, e.g. Response.Write(txt.Text);
}
}
}
I have a small program that generates four dynamic buttons on load in a flowLayoutPanel1 and a static save button.
My aim is to save the dynamic button colors so that when the form is reloaded or opened again the colors of the dynamic buttons are loaded back up in the same state as saved.
Below I will include my code which has been commented to demonstrate what I have attempted.
I am using an xml file to save the button state and included a class that holds the state. However the method I am using works fine if a create my buttons to save statically. (I have only tried it with one static button)
Interface:
class that holds state:
public class MyFormState
{
public string ButtonBackColor { get; set; }
}
Form code:
public partial class Form1 : Form
{
//Form Member
MyFormState state = new MyFormState();
Button btn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//loading xml file if it exists
if (File.Exists("config.xml"))
{
loadConfig();
}
//Genrating dynamic buttons
// flowLayoutPanel1.Controls.Clear();
for (int i = 0; i <= 3; ++i)
{
btn = new Button();
btn.Text = " Equation " + i;
flowLayoutPanel1.Controls.Add(btn);
//click event of buttons
btn.Click += new EventHandler(btn_Click);
}
btn.BackColor = System.Drawing.ColorTranslator.FromHtml(state.ButtonBackColor);
}
//method to load file
private void loadConfig()
{
XmlSerializer ser = new XmlSerializer(typeof(MyFormState));
using (FileStream fs = File.OpenRead("config.xml"))
{
state = (MyFormState)ser.Deserialize(fs);
}
}
//saving the xml file and the button colors
private void writeConfig()
{
using (StreamWriter sw = new StreamWriter("config.xml"))
{
state.ButtonBackColor = System.Drawing.ColorTranslator.ToHtml(btn.BackColor);
XmlSerializer ser = new XmlSerializer(typeof(MyFormState));
ser.Serialize(sw, state);
}
}
int count = 0;
//backcolor change
void btn_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (count == 0)
{
button.BackColor = Color.Red;
count++;
}
else if (count == 1)
{
button.BackColor = Color.Blue;
count--;
}
}
//save file
private void btnSave_Click(object sender, EventArgs e)
{
writeConfig();
}
}
Any suggestions on what i should change so that it works for me? Thanks
Your code works fine but only for the last button. You have 4 buttons but only have one MyFormState object. When creating the buttons you always use the same private field btn. So you need arrays of 4 MyFormState objects and 4 buttons.
MyFormState[] states = new MyFormState[4];
Button[] buttons = new Button[4];
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists("config.xml"))
{
loadConfig();
}
for (int i = 0; i < 4; ++i)
{
buttons[i] = new Button();
buttons[i].Text = " Equation " + i;
flowLayoutPanel1.Controls.Add(buttons[i]);
buttons[i].Click += new EventHandler(btn_Click);
if (states[i] != null)
{
buttons[i].BackColor = ColorTranslator.FromHtml(states[i].ButtonBackColor);
}
}
}
private void loadConfig()
{
XmlSerializer ser = new XmlSerializer(typeof(MyFormState[]));
using (FileStream fs = File.OpenRead("config.xml"))
{
states = (MyFormState[])ser.Deserialize(fs);
}
}
private void writeConfig()
{
for (int i = 0; i < 4; i++)
{
if (states[i] == null)
{
states[i] = new MyFormState();
}
states[i].ButtonBackColor = ColorTranslator.ToHtml(buttons[i].BackColor);
}
using (StreamWriter sw = new StreamWriter("config.xml"))
{
XmlSerializer ser = new XmlSerializer(typeof(MyFormState[]));
ser.Serialize(sw, states);
}
}
I need to make a ListBox that displays how often a Button is clicked.
The user chooses how many buttons are available to click. Here is what I've tried:
int clicked;
clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
for (int i = 0; i < freq_array[clicked]; i++)
lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked];
freq_array uses the 'clicked' variable to add to the frequency that button has been clicked. Or, it's supposed to.
When I debug it, 'clicked' always comes out to 0. I want 'clicked' to equal the text value of the button that's clicked. When I try to run the program, I get an error saying "Input string was not in correct format."
Edit:
I was able to fix my program with help from you guys. I realized I didn't show enough of my code to be clear enough, and I apologize for that. I had to add some things and move things around and got it soon enough. Thank you all.
Here is the code just for those who may need help in the future:
public partial class Form1 : Form
{
int[] freq_array = new int[11];
int[] numList = new int[11];
int oBase = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
invisiblity();
}
private void invisiblity()
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
if (Char.IsDigit(ctrl.Text[0]))
ctrl.Visible = false;
}
}
private void btnSetBase_Click(object sender, EventArgs e)
{
Form2 frmDialog = new Form2();
frmDialog.ShowDialog(this);
if (frmDialog.DialogResult == DialogResult.OK)
{
oBase = frmDialog.Base;
//lblOutDigits.Text = oBase.ToString();
for (int i = 0; i < oBase; i++)
{
numList[i] = i;
}
}
ShowBaseButtons(oBase);
}
private void ShowBaseButtons(int last_digit)
{
invisiblity();
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
if (Char.IsDigit(ctrl.Text[0]))
if (int.Parse(ctrl.Text) <= last_digit - 1)
ctrl.Visible = true;
}
}
private void btnN_Click(object sender, EventArgs e)
{
lblOutDigits.Text += ((Button)(sender)).Text;
int clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
}
private void btnShowFreq_Click(object sender, EventArgs e)
{
lstFrequencies.Items.Clear();
for (int i = 0; i < oBase; i++)
lstFrequencies.Items.Add(numList[i] + " \t\t\t" + freq_array[i]);
}
Your code should work as long as your Button Text is actually just a number. Since what you are trying to do is create an index, what I usually do is use the Tag Property of the control, set it to the Index I want in the designer and then cast that to an Int.
i.e.
if (int.TryParse(((Button)sender).Tag.ToString(), out clicked))
freq_array[clicked]++;
I believe what is happening is that you are not initializing your ListBox, This example Code does work using your initial method. Just create a new Form and paste it in and test.
public partial class Form1 : Form
{
ListBox lstFrequencies = new ListBox();
int[] freq_array = new int[10];
public Form1()
{
InitializeComponent();
Size = new Size(400, 400);
lstFrequencies.Location = new Point(150, 0);
lstFrequencies.Size = new Size(150, 200);
Controls.Add(lstFrequencies);
int top = 0;
for (int i = 0; i < 10; i++)
{
Button btn = new Button();
btn.Size = new Size(70, 30);
btn.Location = new Point(5, top);
Controls.Add(btn);
top += 35;
btn.Tag = i;
btn.Text = i.ToString();
btn.Click += new EventHandler(btn_Click);
lstFrequencies.Items.Add(i.ToString());
}
}
void btn_Click(object sender, EventArgs e)
{
int clicked;
clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked]; //Cleaned up you do not need to iterate your list
// Using my example code
//if (int.TryParse(((Button)sender).Tag.ToString(), out clicked))
//{
// freq_array[clicked]++;
// lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked];
//}
}
}
Your code always comes out to 0 because you never assign last clicked value to button text. Try this code:
int clicked = 0;
private void button1_Click(object sender, EventArgs e)
{
clicked = Convert.ToInt32(((Button)sender).Text);
lstFrequencies.Items.Add(((Button)sender).Name + " " + ++clicked);
button1.Text = clicked.ToString(); // you lose this line
}
EDIT: Counter from variable member
int clicked = 0;
private void button1_Click(object sender, EventArgs e)
{
// if you want to display button name, change .Text to .Name
lstFrequencies.Items.Add(((Button)sender).Text + " " + ++clicked);
}