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:
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?
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);
}
}
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. :)
Try the SelectedItems.Add funcion. You can add to the current selection every item you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.