简体   繁体   English

打开并保存文件对话框

[英]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? 我使用openFileDialog从文本文件中读取并在列表框中打印值,并使用saveFileDialog将更改保存在textfile中。我编写了这段代码,但它不起作用。如果使用文本框更改列表框可以正常工作。我需要打印并将项目保存到listbox.any建议吗?

    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. 您可以使用File.ReadAllLines和listBox1.Items.AddRange添加项目。

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 由于Items属性包含对象,而不是字符串,因此您将需要手动遍历项目并将其分别写入...也许做类似

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. ListBox.Text仅表示列表框项目的选定部分。

A quote from MSDN docs: 来自MSDN文档的报价:

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>());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM