Reading from text file and populate to Listbox with Button - c#

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.

Related

C# Button not firing more than once

When I click the button the first time, it works, but after that, it doesn't do anything. I have tried to debug this and I have looked it up but I can't find an answer. I am probably just not noticing something obvious.
private void button5_Click(object sender, EventArgs e)
{
string[] files;
files = Directory.GetFiles("Tasks");
foreach (string file in files)
{
string[] lines;
StreamReader reader = new StreamReader(file);
lines = File.ReadAllLines(file);
tasks.Add(lines[0]);
reader.Close();
}
listBox1.DataSource = tasks;
}
You're problem is not with the button. It's with the listbox. It's not updating properly because it's not detecting a change in your datasource.
Try setting it to null before updating so it knows it's changing:
listBox1.DataSource = null;
listBox1.DataSource = tasks;
Alternative Method:
You can also use a BindingList instead of a regular list.
See here:
How to refresh DataSource of a ListBox in C# WinForms

saving and returing listbox content C#

I have a question about saving content from a listbox and putting it in a .ini file. Also i want to retrieve the information and put it back in the listbox when the programm starts.
I have two listboxes lets call them listBox1 and listBox2.
And 1 button lets call that selectbttn.
The content from listBox2 must be saved when i click on the select button. ,br />
How can i fix this?
This is the code with the 2 listboxes, id ont have a code for the select button.
The button that you see in the code is a add button that adds content from listbox1 to listbox 2.
private void add_button_Click(object sender, EventArgs e)
{
try
{
if (list_selected.Items.Contains(List_selection.SelectedItem))
{
MessageBox.Show("Can not add the type twice.");
}
else
{
list_selected.Items.Add(List_selection.SelectedItem);
}
}
catch
{
{
MessageBox.Show("No type selected");
}
}
}
You need to use a StreamWriter to save to the file. You could do something like the following:
public void SaveFile_Click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\YourFile.ini"))
{
foreach (var item in list_selected.Items)
{
file.WriteLine(item.ToString());
}
}
}
http://msdn.microsoft.com/en-us/library/vstudio/8bh11f1k.aspx
You can use a StreamReader to read back the contents of the .ini file when your application loads. I will leave this to you since you did not originally provide code.
Write
File.WriteAllLines("test.ini",
listbox.Items.Cast<ListItem>().Select(i => i.Text).ToArray());
Load
listbox.Items.AddRange(File.ReadAllLines("test.ini")
.Select(l => new ListItem(l)).ToArray());

save and load data from .txt to the right texbox

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

open and save file dialog

i use an openFileDialog to read from a text file and print the values in a listbox and a saveFileDialog to save the changes in textfile.i wrote this code but it doesn't work.if a change the listbox with a textbox works fine.But i need to print and save the items into a listbox.any suggestions?
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label7.Text = openFileDialog1.FileName;
listBox1.Text = File.ReadAllText(label7.Text);
}
}
private void button5_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, listBox1.Text);
}
}
You need to add each line of the file as a listbox item. Then, to save, loop through each listbox item and write it as a new line.
You can use File.ReadAllLines and listBox1.Items.AddRange to add the items.
listBox1.Items.AddRange(File.ReadAllLines(openFileDialog1.FileName));
Since the Items property contains objects, not strings, you will need to manually loop over the items and write them individually... perhaps doing something like
StringBuilder sb = new StringBuilder();
foreach(object item in listBox1.Items) {
sb.AppendLine(item.ToString();
}
File.WriteAllText(saveFileDialog1.FileName, sb.ToString());
ListBox.Text represents only a selected part of the list box items.
A quote from MSDN docs:
When the value of this property is set to a string value, the ListBox searches for the item within the ListBox that matches the specified text and selects the item. You can also use this property to determine which items are currently selected in the ListBox
This should work :
using System.Linq;
...
string[] lines = File.ReadAllLines(fileName);
listBox.Items.AddRange(lines.ToArray<object>());

How to overwrite (NOT append) a text file in ASP.NET using C#

I have included a text file in my website with multiple lines.
I have put a textbox (Multimode=true) and a button in the page.
On Page_Load the content from the textFile should be displayed in the textbox.
Then the user can edit the textbox. On button click the current content of TextBox should be overwritten in that text file (it should not be appended).
I'm successfully displaying the text file data in a textbox. But while overwriting, it appends in the text file rather than overwriting.
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (File.Exists(Server.MapPath("newtxt.txt")))
{
StreamReader re = new StreamReader(Server.MapPath("newtxt.txt"));
while ((input = re.ReadLine()) != null)
{
TextBox1.Text += "\r\n";
TextBox1.Text += input;
}
re.Close();
}
else
{
Response.Write("<script>alert('File does not exists')</script>");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StreamWriter wr = new StreamWriter(Server.MapPath("newtxt.txt"));
wr.Write("");
wr.WriteLine(TextBox1.Text);
wr.Close();
StreamReader re = new StreamReader(Server.MapPath("newtxt.txt"));
string input = null;
while ((input = re.ReadLine()) != null)
{
TextBox1.Text += "\r\n";
TextBox1.Text += input;
}
re.Close();
}
How can I overwrite the text file and then display it in my TextBox on the same button click?
StreamWriter constructor has several overloads, including one to specify whether to append or overwrite.
StreamWriter wr = new StreamWriter(Server.MapPath("newtxt.txt"), false);
From MSDN, the second parameter:
Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.
Server.MapPath returns a string with the path to the file. You might try opening the file by hand before passing it to the stream writer. Note the FileMode of Create, and the FileAccess of Write.
var path = Server.MapPath("newtxt.txt");
using (var fileStream = File.Open(path, FileMode.Create, FileAccess.Write))
{
using (var writer = new StreamWriter(fileStream))
{
// the rest of your code
}
}
Check out the System.IO.File.WriteAllText method, it'll overwrite the file if it exists and it's all done in just a single line of code. Likewise, you can use the System.IO.File.ReadAllText method to easily get the contents of a file.
protected void Page_Load(object sender, EventArgs e)
{
if (File.Exists(Server.MapPath("newtxt.txt")))
{
TextBox1.Text = System.IO.File.ReadAllText("newtxt.txt");
}
else
{
Response.Write("<script>alert('File does not exists')</script>");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
System.IO.File.WriteAllText("newtxt.txt", TextBox1.Text);
}
You appear to be overwriting the file in your Button Click handler, then appending it's contents to the TextBox. In this way, it appears to the client that you've appended to the file.
Try the following in the Button Click handler, after writing the file and before reading it back:
TextBox1.Text = "";
Or just don't bother reading it back - there's not much point because the text you've written to the file is still in the TextBox.

Categories