-3


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");
            }

        }
    }
4

2 回答 2

2

File.WriteAllLines("test.ini", 
                listbox.Items.Cast<ListItem>().Select(i => i.Text).ToArray());

加载

 listbox.Items.AddRange(File.ReadAllLines("test.ini")
                   .Select(l => new ListItem(l)).ToArray());
于 2013-06-14T09:07:22.337 回答
2

您需要使用 aStreamWriter保存到文件中。您可以执行以下操作:

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

您可以StreamReader在应用程序加载时使用 a 读回 .ini 文件的内容。由于您最初没有提供代码,因此我将把它留给您。

于 2013-06-14T08:57:32.747 回答