Search code examples
c#winformslistboxselectedindex

How can I position a listbox to an item with a specific Valuemember?


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.


Solution

  • You can use the SelectedItem property and pick the item you want

    Using the struct you provided, here's a quick sample:

        private void button1_Click(object sender, EventArgs e)
        {
            cmbMarkers.DataSource = null;
            var markerList = new List<MarkerRecord>
            {
                new MarkerRecord(1, "first"), new MarkerRecord(2, "second")
            };
            cmbMarkers.ValueMember = "MarkerId";
            cmbMarkers.DisplayMember = "MarkerName";
            cmbMarkers.DataSource = markerList;
            cmbMarkers.SelectedItem = markerList.FirstOrDefault(mr => mr.MarkerId == 2); //second item selected
        }
    

    On the last line, you get to choose which item you want selected.