open and save file dialog
i use an openFi开发者_如何学GoleDialog 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>());
精彩评论