save and load data from .txt to the right texbox - c#

I want to use a .txt file instead of a XML and I want to keep using the WriteAllLineS/WriteAllText and ReadAllLines/ReadAllText.
I have two text boxes 1 & 2 and next to them is a "save" and "load" button - one for each textbox.
My code so far replicates the data from the first box into the second one. Here is the listing:
public partial class Form1 : Form
{
string fileName = "Cache/textBoxdata.txt";
public Form1()
{
InitializeComponent();
}
private void load1_Click_1(object sender, EventArgs e)
{
textBox1.Lines = File.ReadAllLines(fileName);
}
private void Save1_Click_1(object sender, EventArgs e)
{
File.WriteAllLines(fileName, textBox1.Lines);
}
private void load2_Click(object sender, EventArgs e)
{
textBox2.Lines = File.ReadAllLines(fileName);
}
private void save2_Click(object sender, EventArgs e)
{
File.WriteAllLines(fileName, textBox2.Lines);
}
}
I want to be able to write text in the two text boxes, click the "save" button - this should write entered text to the file. Then, once I reopen the app click the "load" button, my data should be loaded from the file and appear in the text box.
At the moment my first text box works. Second text box shows what I wrote in the first one - not the second one.

Why do you have two save/load buttons? Your question is about saving/loading both textboxes at once. So you need only one button for each operation.
To save/load the lines of a textbox into/from a file you can use WriteAllLines and ReadAllLines as you already do. Since you want to have only one file you need to know where the lines for the first textbox end and the second begins. The easiest way to do so is to write the number of lines into the file:
private void SaveTextboxes()
{
List<string> linesToSave = new List<string>();
linesToSave.Add(textBox1.Lines.Length.ToString());
linesToSave.AddRange(textBox1.Lines);
linesToSave.Add(textBox2.Lines.Length.ToString());
linesToSave.AddRange(textBox2.Lines);
File.WriteAllLines(filename, linesToSave);
}
private void LoadTextboxes()
{
string[] loadedLines = File.ReadAllLines(filename);
int index = 0;
int n = int.Parse(loadedLines[index]);
string[] lines = new string[n];
Array.Copy(loadedLines, index + 1, lines, 0, n);
textBox1.Lines = lines;
index += n + 1;
n = int.Parse(loadedLines[index]);
lines = new string[n];
Array.Copy(loadedLines, index + 1, lines, 0, n);
textBox2.Lines = lines;
}
If you add more textboxes you can repeat this for the desired number of textboxes. Build an array of the textboxes and loop through it.
If you really want to have separate save/load buttons for each textbox this might be a bit more confusing since you only want to overwrite a part of the text. Basically this means that on save you first read the whole file into two separate arrays and then write them back with the respective array being replaced by the new text.

of course is the text in the textbox the same after loading - you are using the same file ...
you can save the content into two different files, then it should work

Related

Dont Save Item in ComboBox

I have a TextBox, a Button, and a Combobox
When I click the Button, I want the text in Textbox to be added to the Combobox Items
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Items.Add(textBox1.Text);
}
My form until open. This text shows in the Combobox, but when I close the Form and open it again the text is not longer shown in the Combobox.
I want to save the text to the Collection Items of the Combobox. I don't want to use a database.
As others have mentioned in the comments, you need to understand and decide where you wish to store your values.
For the purpose of my example, I have created a simple text file to store these values. The code reads from the file and adds each line as an item into the ComboBox.
private void Form1_Load(object sender, EventArgs e)
{
// Read items from file into a string array
string[] items = System.IO.File.ReadAllLines(#"D:\ComboBoxValues.txt");
// Add items to the comobobox when opening the form
comboBox1.Items.AddRange(items);
}
private void button1_Click(object sender, EventArgs e)
{
// Add your new value to the combobox
comboBox1.Items.Add(textBox1.Text);
// Put all existing comobo box items into a string array
string[] items = comboBox1.Items.OfType<string>().ToArray();
// Save the array of items to a text file (this will not append, it will re-write the file)
System.IO.File.WriteAllLines(#"D:\ComboBoxValues.txt", items);
}
This may not be the most elegant way of going about it, but from the point of providing you an understanding - this should be more than sufficient.
if you don't like to use File System, you can use Preferences(but it's not recommendable to use preference to memorize large values), check this link to see how create a new setting
private void Form1_Load(object sender, EventArgs e)
{
string[] strItems = Properties.Settings.Default.items.Split(", ");
for(int i = 0; i < strItems.length; i++) {
comboBox1.Items.Add(strItems[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
//add your new value to the combobox
comboBox1.Items.Add(textBox1.Text);
//put all existing combo box items into a string array
string[] items = comboBox1.Items.OfType<string>().ToArray();
for(int i = 0; i < items.length; i++) {
//I assumed you had an items key in your settings
if(i == items.length - 1) {
Properties.Settings.Default.items += value;
} else {
Properties.Settings.Default.items += value + ", ";
}
}
//then you should to save your settings
Properties.Settings.Default.Save();
}

Reading from text file and populate to Listbox with Button

I am trying to create a window program where the program reads from a text file and display the data in a listbox. I have tried the below coding but the problem now is that every time I click on the button, it will append and the data will repeat.
How do I do it so that it reads the file and only include new input data?
private void Button_Click(object sender, RoutedEventArgs e)
{
using (StreamReader sr = new StreamReader("C:\\Users\\jason\\Desktop\\Outbound.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Listbox1.Items.Add(line);
}
sr.Close();
}
}
The probably most simple way to do what you want is to read all lines from the file into a collection, and then assign that collection to the ItemsSource property of your ListBox:
private void Button_Click(object sender, RoutedEventArgs e)
{
Listbox1.ItemsSource = File.ReadAllLines(#"C:\Users\jason\Desktop\Outbound.txt");
}
As Clemens said in comment, you can either Listbox1.Items.Clear() or Listbox1.ItemsSource = File.ReadAllLines(#"C:\Users\jason\Desktop\Outbound.txt");
But this would always replace all your listbox with the file. If you just want, as you said, to enter new data, you could simply check if if(!Listbox1.Items.Contains(line)) before adding the item.
Depends on what you really want, reupdate the whole list or just add new entries and not removing old ones.

How can i read the text from richTextbox and keep the format of the text?

For example inside the richTextBox I have the text:
Hello world
Hello hi
Hi all
Now I want to read this text with this format including the empty line/s and then to write back to the same file the same text with or without changes like deleted text or added text.
For example, if I delete the all then the text to write back will be in this format:
Hello world
Hello hi
Hi
Just without the all
Or
Hello world
Hello hi
Hi all everyone
So now it will write the same text but with the everyone but will keep the format.
I tried this but this adding too many empty lines and spaces that was not before:
var lines = richTextBox1.Text.Split('\n');
File.WriteAllLines(fileName, lines);
Then i tried:
var text = richTextBox1.Text;
File.WriteAllText(fileName, text);
This wrote to the file the same text with the changes but it didn't keep the format it wrote the text to the file as one line.
You have to replace "\n" with "\r\n"
var text = richTextBox1.Text;
text = text.Replace("\n", "\r\n");
File.WriteAllText(fileName, text);
Well, there are a several options here, none of which involve splitting the text.
Note: All the code below is using a private variable that has the file path as a string:
public partial class Form1 : Form
{
private const string filePath = #"f:\public\temp\temp.txt";
The first one is to simply save all the text (including the \r\n characters) using the Text property, along with File.ReadAllText and File.WriteAllText:
// Load text on Form Load
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists(filePath))
{
richTextBox1.Text = File.ReadAllText(filePath);
}
}
// Save text on button click
private void button1_Click(object sender, EventArgs e)
{
File.WriteAllText(filePath, richTextBox1.Text);
}
If you want to do it line by line, you can use File.ReadAllLines and File.WriteAllLines along with the Lines property of the RichTextBox:
// Load text on Form Load
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists(filePath))
{
richTextBox1.Lines = File.ReadAllLines(filePath);
}
}
// Save text on button click
private void button1_Click(object sender, EventArgs e)
{
File.WriteAllLines(filePath, richTextBox1.Lines);
}
Finally, you could use the built-in SaveFile and LoadFile methods of the RichTextBox class. This method will write metadata to the file, so if you open it in notepad you will see some additional characters that include all kinds of format information. Because of this, I added a try/catch block around the call to LoadFile, since it will throw and exception if the file does not have the correct format, and I fall back to loading it with ReadAllText:
// Load text on Form Load
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists(filePath))
{
try
{
richTextBox1.LoadFile(filePath);
}
catch (ArgumentException)
{
// Fall back to plain text method if the
// file wasn't created by the RichTextbox
richTextBox1.Text = File.ReadAllText(filePath);
}
}
}
// Save text on button click
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.SaveFile(filePath);
}

c# putting inputs into next array elements automatically

Is there a way to put text or variables into the next array element without directly referencing what array element you want it in? For example:
private void btnAdd_Click(object sender, EventArgs e)
{
TextBox1.Text = array[0];
}
How could I get this to instead put it into element 0 but every time the button is clicked it automatically puts it into the next available one, array[0] then array[1].
My goal for this is that I have a large portion of code that only works for one array element but if I could automatically send the input into the next element I can just redirect each event handler to a new method containing the portion of code which would save me from just copy and pasting the code 5 times and just changing the element ID's.
Use List<string> array instead of string[] array
Example code:
private List<string> array = new List<string>();
private void btnAdd_Click(object sender, EventArgs e)
{
array.Add(TextBox1.Text);
}
Define a field called indexValue of type integer and increase it on every click event. For example:
private int indexValue; // defines a field to keep the current index
private void btnAdd_Click(object sender, EventArgs e)
{
array[indexValue++] = TextBox1.Text; // assigns the value entered by the user to the array on the next position
}

How to make text display in a textbox multiple times in C#?

I want to display something multiple times in a textbox. For example if you use this code and replace richtextbox with messagebox, it will keep displaying the text until the loop ends. I want to display the text from textBox1 into richTextBox1, and then have the program hit enter, and then type it out again in the richtextbox. It's kind of confusing sorry, but if you have any questions just comment them and i'll be more clear. This is my code:
private void button1_Click(object sender, EventArgs e)
{
Clipboard.SetText(textBox1.Text);
int text = 0;
int end = int.Parse(textBox2.Text);
while (text<=end)
{
richTextBox1.Text=(Clipboard.GetText());
text++;
}
Thanks in advance!
In your code you have:
richTextBox1.Text=(Clipboard.GetText());
The reason that your code is not working is because in every loop, you are setting the text to whatever is on the clipboard, so at the end of the loop it will only have it in there once. You need to 'append' or add onto the end of the text so it will have it multiple times:
richTextBox1.Text += richTextBox1.Text + (Clipboard.GetText());
Or:
richTextBox1.Text += (Clipboard.GetText());
This will add the clipboard text onto the end of the RichTextBox, so you will have the same text multiple times, but all on the same line. If you want to make the text appear on multiple lines, you have to add a new line after appending the text:
richTextBox1.Text += (Clipboard.GetText())+"\r\n";
Or:
richTextBox1.Text += (Clipboard.GetText())+Enviroment.NewLine;
Hope this Helps!
Use Timer instead of using loop and keep its interval time like for 2 second. and on button click start timer and declare end as class variable , when condition is met for "end" variable , stop timer.
private void button1_Click(object sender, EventArgs e)
{
end = int.Parse( textBox2.Text);
timer1.Start();
}
private int end = 0;
private int start = 0;
private void timer1_Tick(object sender, EventArgs e)
{
if (start == end)
{
timer1.Stop();
}
else
{
start++;
textBox1.Text = start.ToString();
}
}

Categories