I have a winform with a listbox with a datasource of list of struct, where the struct is:
public struct MakerRecord
{
public int MakerID { get; set; }
public String MakerName { get; set; }
public MakerRecord(int ID, String Name)
{
MakerID = ID;
MakerName = Name;
}
}
and listbox.ValueMember = "MakerID" and listbox.DisplayMember = "MakerName"
The user can either select an item and the text (i.e. MakerName) is loaded to a textbox where it can be edited, or click an Add button and get an empty textbox.
After making changes to the textbox, the User clicks a Save button and the record is saved back to Database and the listbox is refreshed - which sets the SelectedIndex = -1.
All good.
But I want to position the listbox back to the record that was edited (or added) and all I have is the MakerID from the db operation. So how can I set SelectedIndex from just the value member?
Setting SelectedValue (i.e. lstbox.SelectedValue = MakerID) does not effect the SelectedIndex naturally.
You can use the
SelectedItem
property and pick the item you wantUsing the struct you provided, here's a quick sample:
On the last line, you get to choose which item you want selected.