I have a WinForm of 15 textboxes in a row and each one has a save and show button next to it. The user can write text in these boxes and when they open the form they can click show and view the text they wrote and then save it and close the app and its still there to be shown.
For the code I thought I could use it individually on each textbox and button
namespace UniversityProject
{
public partial class managementsystem : Form
{
private const string fileName = #"C:\txtBoxdata.txt";
public managementsystem()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox3.Text = File.ReadAllText(fileName);
}
private void button2_Click(object sender, EventArgs e)
{
File.WriteAllText(fileName, textBox3.Text);
}
I thought it would work by changing the textBox numbers but I think it might have something to do with the read all. As all the textboxes show the same data which is incorrect.
Let me try to clarify your question:
You have a bunch of textboxes where each represents a single line in a text file. Each time the user clicks on a button next to a textbox you want to replace the corresponding line.
Replacing a single line in a text file is quite easy. Just read all the lines into an array, replace the line and write everything back to the file:
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);
}
}
The only thing left is to know which line should be replaced. You can add a handler for each button (notice that the line numbers start with 0):
private void button1_Click(object sender, EventArgs e)
{
ReplaceLineInFile(fileName, 0, textBox1.Text);
}
private void button2_Click(object sender, EventArgs e)
{
ReplaceLineInFile(fileName, 1, textBox2.Text);
}
etc.
This is not very elegant because it duplicates the same code. It would be better to use a single event handler for all buttons and then figure out which textbox it adresses and which line should be replaced. I would recommend to have arrays for the textboxes and buttons and build them in the constructor:
private TextBox[] textBoxes;
private Button[] buttons;
public managementsystem()
{
InitializeComponent();
textBoxes = new TextBox[] { textBox1, textBox2, textBox3, textBox4, textBox5 };
buttons = new Button[] { button1, button2, button3, button4, button5 };
}
Your single event handler would be:
private void button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{
int lineNumber = Array.IndexOf(buttons, button);
if (lineNumber >= 0)
{
ReplaceLineInFile(fileName, lineNumber, textBoxes[lineNumber].Text);
}
}
}
At some point you might want to save all values and/or create the file. Also you might want to load existing values into your textboxes when the form is loaded:
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));
}
Notice that this will still work when you add new textboxes. The only thing you have to change is the creation of the arrays in the constructor. However, if you change the number of textboxes this will delete the existing file. To avoid this you can add or remove new lines manually.
The basic problem is you are trying to save different textbox values into one txt file. Change the txt file-names along with the textBox names, and you will be good to go .. :)
Get a hold of StreamWriter and StreamReader.
Open a new stream with either stream-writer or reader in your OnClick-events. Then use something like
using(StreamWriter sw = new StreamWriter("C:\\Path\\to\\file.txt")){
sw.WriteLine("TEXTBOX1: " + textbox1.text);
sw.Close();
}
Do this for all your textboxes. And eventually use the StreamReader to read from your file
using(StreamReader sr = new StreamReader("C:\\Path\\to\\file.txt")){
string s = sr.ReadToEnd();
//find value for your textbox;
textbox1.Text = s;
sw.Close();
}
Give it a shot!
Related
I was wondering if it possible for WPF to save the radio button content and use the event handler to sent the content to text file. Do I need to do all that in the event handler or i can invoke some class?
public void method(){
string s = "Test1&Test2&Test3&Test4";
string[] s = Spliting.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries);
List<RadioButton> radioButtonList = new List<RadioButton>();
radioButtonList.Add(radioButton);
radioButtonList.Add(radioButton1);
for (int i = 0; i < radioButtonList.Count; i++)
{
//some code that insert string into the radio button (done)
//when i use streamwriter inside here, it give me this in the text file
//System.Windows.Controls.RadioButton Content IsChecked:False <- this can be turn to true if i put variable.Checked = true
}
private void radioButton_Checked(object sender, RoutedEventArgs e)
{
if (radioButton.IsChecked == true)
{
StreamWriter streamwriters = new StreamWriter ("Sent.txt", false);
streamwriters.Close();
}
else if (radioButton1.IsChecked == true)
{
StreamWriter streamwriters = new StreamWriter("Sent.txt", false);
streamwriters.Close();
}
Or WPF have a method that can automatically save the content into variable. Am I missing something?
I wanted the radio button to check the radio button and sent the content into the text file.
If you just want to save the text displayed with the radio button to a file, then:
private void radioButton1_Checked(object sender, EventArgs e)
{
string radioButtonContent = ((RadioButton)sender).Text;
string savePath = #"C:\sent.txt"; // or wherever
File.WriteAllText(savePath, radioButtonContent);
}
I have a program with a combo box, a list for that box and a string.
The string is created from user input via a text box and is saved each time the program closes. So if I type "Input Text" then close and open the program the combo box will have a list containing 1 string which displays "Input Text"
The issue is I want to keep adding to the list with new information but at the moment its just constantly overriding what I put in last time.
How do I add to my list with a new item each time the string is different?
private void Form1_Load(object sender, EventArgs e)
{
//Load Settings
saveLocationTextBox.Text = MySettings.Default["SaveSaveLocationText"].ToString();
List<string> list = new List<string>();
list.Add(saveLocationTextBox.Text);
comboBox.DataSource = list;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//Save User Input
MySettings.Default["SaveSaveLocationText"] = saveLocationTextBox.Text;
MySettings.Default.Save();
}
The problem is that you are saving only the selected item text in your settings, not all the items in the combo box.
I suggest to get all the items in the combo first and put them in a comma delimited string.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//Save User Input
string[] itemsToStore = new string[comboBox.Items.Count];
for (int i = 0; i < comboBox.Items.Count; i++)
{
itemsToStore[i] = comboBox.GetItemText(comboBox.Items[i]);
}
MySettings.Default["SaveSaveLocationText"] = saveLocationTextBox.Text;
MySettings.Default["SaveSaveLocationItems"] = string.Join(",", itemsToStore);
MySettings.Default.Save();
}
private void Form1_Load(object sender, EventArgs e)
{
//Load Settings
saveLocationTextBox.Text = MySettings.Default["SaveSaveLocationText"].ToString();
string listItems = MySettings.Default["SaveSaveLocationItems"].ToString();
List<string> list = new List<string>();
list.AddRange(listItems.Split(','));
comboBox.DataSource = list;
}
instead of overriding the text in the file do:
var items = comboBox.Items.Select(item => comboBox.GetItemText(item)).ToList();
items.Add(saveLocationTextBox.Text);
MySettings.Default["SaveSaveLocationText"] = string.Join(";", items);
And then when reading it:
var text = MySettings.Default["SaveSaveLocationText"].ToString();
comboBox.DataSource = text.Split(';').ToList();
I have a windows form that reads strings from a file and shows them all in a textbox when I press a button.
private void buttonTxt_Click(object sender, EventArgs e)
{
string[] Test = File.ReadAllLines("C:\\testfile.txt");
for (int i = 0; i < testfile.Length; i++)
{
TextBox.Text += testfile[i];
}
}
I'd like to make two radio buttons. So that first button lets my program work the way I described (by default) AND second radio button makes it work vice versa -- so that I could write in a textbox myself and when I press a button it writes a new line to the same file. Is there a way to do it?
Simply add an if statement in this event handler and implement both sending and receiving the data. Done. Sample in principle:
private const string FilePath = #"C:\testfile.txt";
private void buttonTxt_Click(object sender, EventArgs e)
{
if (radioReadMode.Checked) // check which radio button is selected
{ // read mode
string[] Test = File.ReadAllLines(FilePath);
for (int i = 0; i < testfile.Length; i++)
TextBox.Text += testfile[i];
}
else
{ // write mode
File.WriteAllText(FilePath, TextBox.Text);
}
}
I believe this is what you might be looking for. If radio button 1 is checked then if the file exists it will read that file and put it into a textbox in the form. If you switch to radio button 2. You can type in the text box and then when you press the button it will append it to the file.
public partial class Form1 : Form
{
System.IO.StreamReader sr;
System.IO.StreamWriter sw;
public Form1()
{
InitializeComponent();
radioButton1.Checked = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sr = new System.IO.StreamReader("C:\\testfile.txt");
while (!sr.EndOfStream)
{
textBox1.Text += sr.ReadLine() + "\r\n";
}
}
finally
{
sr.Close();
sr.Dispose();
}
}
}
if (radioButton2.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sw = new System.IO.StreamWriter("C:\\testfile.txt", true);
string result = textBox1.Text;
string[] lststr = result.Split(new Char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in lststr)
{
sw.WriteLine(s);
}
}
finally
{
sw.Flush();
sw.Close();
sw.Dispose();
}
}
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = true;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = false;
}
}
Yes, there's a way. Just add another button to your form and inside read the text from the text box this way:
var textBoxContent = TextBox.Text;
and save it to your file this way
File.WriteAllText("C:\\testfile.txt", textBoxContent);
Note: I recommend getting the path to your file into a variable
Right now my code takes the entire text file and just places it all into one text box. What I am trying to figure out how to do is have it place each line of the file into each separate text box.
namespace HomeInventory2
{
public partial class Form1 : Form
{
public Form1(string prepopulated)
{
InitializeComponent();
textBoxAmount.Text = prepopulated;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void submitButton_Click(object sender, EventArgs e)
{
CreateInventory create = new CreateInventory();
create.ItemAmount = textBoxAmount.Text;
create.ItemCategory = textBoxCategories.Text;
create.ItemProperties = textBoxValue.Text;
create.ItemValue = textBoxValue.Text;
InventoryMngr invtryMngr = new InventoryMngr();
invtryMngr.Create(create);
}
}
Assuming that the order of the lines is always the same and that each TextBox belongs to a line:
IEnumerable<String> lines = File.ReadLines(path);
textBoxAmount.Text = lines.ElementAtOrDefault(0);
textBoxCategories.Text = lines.ElementAtOrDefault(1);
textBoxValue.Text = lines.ElementAtOrDefault(2);
...
Enumerable.ElementAtOrDefault<TSource> Method
Returns the element at a specified index in a sequence or a default
value if the index is out of range (null in this case).
You could use System.IO.File.ReadAllLines(string filename).
What this does is reads each line of the file into a String array.
You could then do something like:
using System.IO;
//Namespace, Class Blah Blah BLah
String[] FileLines = File.ReadAllLines("Kablooey");
textBox1.Text = FileLines[0];
textbox2.Text = FileLines[1];
And so on. I hope this helps :)
I need help to get a response when I click on an "Item" from a list view. Know that there is selectedindexchanged, but when I try to display a MessageBox so nothing happens, have tried lots of other things but have not managed to come up with something.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
...
while (reader.Read())
{
string alio = reader["fornamn"].ToString();
string efternamn = reader["efternamn"].ToString();
ListViewItem lvi = new ListViewItem(alio);
listView1.Items.Add(lvi);
lvi.SubItems.Add(efternamn);
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
Assuming that 81.private void listView1_SelectedIndexChanged is properly linked to the listview, you will need to query the listview to find out what's selected:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if(this.listView1.SelectedItems.Count == 0)
return;
string namn = this.listView1.SelectedItems[0].Text;
// Create the sql statement to retrieve details for the user
string sql = string.Format("select * from kunder where fornamn = '{0}', namn);
// do the same as you do to create a reader and update the controls.
}
Going by the term "when I try to display a MessageBox so nothing happens"\, I assume that you simply put MessageBox.Show("blah"); inside the event handler and never got it shown.
If that's the case, your event handler is not hooked properly to your form's list view. go back and see the text listView1_SelectedIndexChanged is anywhere to be found inside your Form1.Designer.cs file.
If not (or anyway), start over on a new form. That's the easiest way out. :)
private void lstView_KQ_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstView_KQ.SelectedItems.Count > 0)
{
ListViewItem itiem = stView_KQ.SelectedItems[lstView_KQ.SelectedItems.Count - 1];
if (itiem != null)
foreach (ListViewItem lv in lstView_KQ.SelectedItems)
{
txtMaNV.Text = lv.SubItems[0].Text;
cmbCV.Text = lv.SubItems[1].Text;
txtHoNV.Text = lv.SubItems[2].Text;
txtTenNV.Text = lv.SubItems[3].Text;
txtNgaysinh.Text = lv.SubItems[4].Text;
txtGioiTinh.Text = lv.SubItems[5].Text;
txtDiaChi.Text = lv.SubItems[6].Text;
txtSDT.Text = lv.SubItems[7].Text;
txtCMND.Text = lv.SubItems[8].Text;
}
}
}