user42348
user42348

Reputation: 4319

How do I get the selected values in a listbox?

I have a Winforms applicaiton that has a listbox of values that can be selected. I want the selected values to show up on the editing form as selected. Here's the loading code:

ListBox Loading Code

private void LoadListBox()
{
    DataTable dt = new DataTable();
    string[] names = new string[] { "UID1", "UID2", "UID3","UID4" };
    dt.Columns.Add("Units", typeof(string));
    dt.Columns.Add("Value", typeof(int));
    int count = 1;
    foreach (string value in names)
    {
        DataRow drRow = dt.NewRow();
        drRow["Units"] = value;
        drRow["Value"] = count;
        count++;
        dt.Rows.Add(drRow);
    }
    listBox1.DisplayMember = "Units";
    listBox1.ValueMember = "Value";
    listBox1.DataSource = dt;
}

If they select UID1 and UID2 it is stored as 1,2 in the database.

If the user clicks on the edit button, then UID1, UID2 should be the selected values, but all values should be loaded.

How do I make sure that whatever they've selected shows as selected when the edit button is clicked?

Upvotes: 0

Views: 2287

Answers (3)

Shadow Wizard
Shadow Wizard

Reputation: 66389

The selected values are preserved during Postback unless you're setting the data source in Postback event as well, thus "overwriting" it.

So just have such if statement in your code:

if (!Page.IsPostBack)
   LoadListBox();

Sorry, thought it was ASP.NET - not relevant in WinForms environment. Other answers already give what you need. :)

Upvotes: 0

Matteo TeoMan Mangano
Matteo TeoMan Mangano

Reputation: 430

Try the SelectedItems.Add funcion. You can add to the current selection every item you want.

Upvotes: 0

John Arlen
John Arlen

Reputation: 6689

Enumerate each listbox item and set it as selected or not based on your rules:

for (int index = 0; index < listBox1.Items.Count; index++ )
{
   Object o = (int)listBox1.Items[index];
   if ( /* criteria you want here */ )
   {
       listBox1.SetSelected(index, true);

}

}

Upvotes: 2

Related Questions