ListBox.DataSource = DataTable... How to Set Selected?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Ok, I have a DataTable:

ID Name
-- ------------
1 John
2 Jacob
3 Jingleheimer
4 Schmidt
5 John


I have set my DisplayMember of my listbox to "Name"; my valueMember to "ID"
and my datasource to myDataTable. So far so good. It shows the list, and
all is well.

What I need to do is be able to set the Selected Item via code. I have done
everything I can think of here, and nothing seems to work. I have tried:

myListBox.SelectedValue = 5 (this is the obvious one that should have worked)
myListBox.SelectedItem = mySelectedRow (a valid reference to the selected
rowview)
myListbox.SetSelected("John", True) This sets the first John, not the
second one.
myListbox.FindString ("John") same problem as above.

I've done this before... What simple thing am I missing here???
 
Hi,

myListBox.SelectedIndex = 4

http://msdn.microsoft.com/library/d...indowsformslistboxclassselectedindextopic.asp


Ken
----------------------
Ok, I have a DataTable:

ID Name
-- ------------
1 John
2 Jacob
3 Jingleheimer
4 Schmidt
5 John


I have set my DisplayMember of my listbox to "Name"; my valueMember to "ID"
and my datasource to myDataTable. So far so good. It shows the list, and
all is well.

What I need to do is be able to set the Selected Item via code. I have done
everything I can think of here, and nothing seems to work. I have tried:

myListBox.SelectedValue = 5 (this is the obvious one that should have
worked)
myListBox.SelectedItem = mySelectedRow (a valid reference to the selected
rowview)
myListbox.SetSelected("John", True) This sets the first John, not the
second one.
myListbox.FindString ("John") same problem as above.

I've done this before... What simple thing am I missing here???
 
Fine solution, provided you know the index is 4...

However, I only know the ID I want is 5...

-Zorpy
 
Check that the SelectedValue is set to a string. Listbox will not do an automatic conversion to find it if it is not.

Example :
dim myID as integer = 4
Listbox.SelectedValue = myID 'does not work

ListBox.SelectedValue = CStr(myID) 'does work
 
Get listBoxchecked item text and value

Code:
foreach (ListItem item in listBoxName.Items)
                {
                    if (item.Checked)
                    {
                        psbo.UserId = int.Parse(item.Value);
                        psbo.UserAdSoyad = item.Text;
                    }
                    
                }

set listBox items checked
vice versa
 
Back
Top