Setting selected item in a ListBox without looping
Asked Answered
A

7

8

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:

DataTable copytable = null;
                copytable = GlobalTable.Copy(); // GlobalTable is a DataTable
                copytable.Rows[0][0] = "--ALL--";
                copytable.Rows[0][1] = "--ALL--";

                breakTypeList.DataSource = copytable;
                this.breakTypeList.DisplayMember = copytable.Columns[0].ColumnName; // description
                this.breakTypeList.ValueMember = copytable.Columns[1].ColumnName; // value
                this.breakTypeList.SelectedIndex = -1;

I am setting description as the DisplayMember and value as the ValueMember of the ListBox. Now depending on what the value is passed I need to set the selected item in the ListBox.

Here's my code:

ListBox lb = c as ListBox;
lb.SelectedValue = valuePassedByUser;

which is not working. Hence I have to resort to the code below (where I loop through all the items in the list box)

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

I would like to know what is missing/ erroneous in my code. Why is lb.SelectedValue = valuePassedByUser; selecting incorrect items?

Apus answered 18/5, 2009 at 12:37 Comment(2)
Can you give some more information on what exactly you need to do or a more complete example of the code? Is the object to read a field from a database and set the selected index/value to a matching value in the listbox?Chesser
The list box is getting populated with a DataTable which in turn has data retrieved from the database. My concern is if I have set the ValueMember while populating the list, why is lb.SelectedValue = valuePassedByUser; not working?Apus
A
7

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;
        }
    }
}
Apus answered 14/7, 2009 at 4:14 Comment(0)
C
1

I think the only way you'll be able to select multiple items is by using a foreach loop. The SelectedValue property only seems to return 1 item. If you want to select more then 1 item you'll have to use :

var tempListBox = c As ListBox;
if (tempListBox != null)
     (tempListBox.SelectedItems.Add(tempListBox.Items[tempListBox.FindStringExact(fieldValue)]);

Also the FindStringExact doesn't search through the Value fields it only looks through the displayed text. Also to cut down on code might want to cast a new variable as a listbox so you don't keep casting C as a listbox.

Crossfertilization answered 18/5, 2009 at 13:42 Comment(0)
L
0

Try this:-

 var listBox = c as ListBox;
    var item = listBox.Items.FindByValue(fieldValue);
    if (item != null)
     listBox.SelectedValue = fieldValue;
Lurdan answered 18/5, 2009 at 13:12 Comment(1)
There is no FindByValue on the Items collection.Crossfertilization
K
0

You can use "FindByValue" like this:

ListBox.SelectedIndex = ListBox.Items.IndexOf(ListBox.Items.FindByValue(fieldValue))
Kaleena answered 2/8, 2010 at 7:38 Comment(0)
A
0
this.Character.SetSelected(this.Character.Items.IndexOf(this.textBox1.Text),true);
Adust answered 23/3, 2016 at 6:22 Comment(0)
R
0

Here's how I solved it, using winforms, DotNet 4.6

listBox1.SelectedIndex = listBox1.FindString(stringInList);
Rosa answered 17/8, 2016 at 1:31 Comment(0)
F
0

If you do not want looping for selected items then retrieve selected value of list box from the listBox_SelectedIndexChanged event and add that value in global array. Then by accessing that array you would get desire selected items value of itemlist with out any loop.

Flirtation answered 17/8, 2016 at 7:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.