Setting selected item in a ListBox without looping

后端 未结 7 1593
萌比男神i
萌比男神i 2020-12-31 19:00

I have a multi-select listbox which I am binding to a DataTable. DataTable contains 2 columns description and value.

Here\'s the listbox populating code:

         


        
7条回答
  •  天命终不由人
    2020-12-31 19:09

    Ok ... here comes hard-to-digest answer which I realized only yesterday. It's my mistake though that I didn't mention one important thing in my question because I felt it is irrelevant to problem at hand:

    The data in the data table was not sorted. Hence I had set the listbox's Sorted property to true. Later I realized When the listbox's or even combo box's sorted property is set to true then the value member does not get set properly. So if I write:

    lb.SelectedValue = valuePassedByUser;

    it sets some other item as selected rather than settting the one whose Value is valuePassedByUser. In short it messes with the indexes.

    For e.g. if my initial data is:

    Index   ValueMember DisplayMember
    1          A            Apple
    2          M            Mango
    3          O            Orange
    4          B            Banana
    

    And I set sorted = true. Then the listbox items are:

    Index   ValueMember DisplayMember
    1          A            Apple
    2          B            Banana
    3          M            Mango
    4          O            Orange
    

    Now if I want to set Banana as selected, I run the stmt:

    lb.SelectedValue = "B";

    But instead of setting Banana as selected, it sets Orange as selected. Why? Because had the list not been sorted, index of Banana would be 4. So even though after sorting index of Banana is 2, it sets index 4 as selected, thus making Orange selected instead of Banana.

    Hence for sorted listbox, I am using the following code to set selected items:

    private void SetSelectedBreakType(ListBox lb, string value)
    {
        for (int i = 0; i < lb.Items.Count; i++)
        {
            DataRowView dr = lb.Items[i] as DataRowView;
            if (dr["value"].ToString() == value)
            {
                lb.SelectedIndices.Add(i);
                break;
            }
        }
    }
    

提交回复
热议问题