Ari
Ari

Reputation: 337

Saving content of particular ListBox control to text file depending on ComboBox selection

I have two ListBox controls in my application and a button to save it to a text file. But I want to select using a ComboBox which one to save to save in a text file. The following code illustrates what I am trying to do:

private void button4_Click(object sender, EventArgs e)
{
    var ss = listBox1.Items;//first listbox
    var sb = listBox2.Items;//second listbox        

    SaveFileDialog svl = new SaveFileDialog();
    svl = saveFileDialog1;
    svl.Filter = "txt files (*.txt)|*.txt";
    if (svl.ShowDialog() == DialogResult.OK)
    {
        using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
            using (StreamWriter st = new StreamWriter(S))
                foreach (string a in ss) // In here i want set which lisbox I want to save
                    st.WriteLine(a.ToString());
    }
}

What would be a good approach to the problem?

Upvotes: 1

Views: 255

Answers (1)

rene
rene

Reputation: 42494

If you add a combobox that holds two items, Listbox1 and Listbox2 the following code will save the items from the listbox selected in the Combobox.

As you can see I add an items local variable that is of type ObjectCollection that is then assigned to using a switch statement.

    private void button4_Click(object sender, EventArgs e)
    {
        ObjectCollection items = null;
        switch (combobox1.Text) {
           case "ListBox1":
                items = listBox1.Items;
           break;
           case "ListBox2":
                items = listBox2.Items;
           break;
           default:
               throw new Exception("no selection");
           break;
        }

        SaveFileDialog svl = new SaveFileDialog();
        svl = saveFileDialog1;
        svl.Filter = "txt files (*.txt)|*.txt";
        if (svl.ShowDialog() == DialogResult.OK)
        {
            using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
            using (StreamWriter st = new StreamWriter(S))
                foreach (string a in items) //the selected objectcollection 
                    st.WriteLine(a.ToString());
        }

If you don't have references to your listboxes you could dynamically add the listboxes that are on the form to the combobox in the load event of the form like so:

foreach(var ctl in this.Controls)
{
    if (ctl is ListBox)
    {
        var lb = (ListBox) ctl;
        this.comboBox1.Items.Add(lb.Name);
     }
}

To find the correct listbox when you click save replace the switch command with this single line:

 var items = ((ListBox) this.Controls[combobox1.Text]).Items;

You might want to check if combobox1.Text is emtpy or null but I leave that as an exercise for the reader.

Upvotes: 1

Related Questions