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

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???
 
K

Ken Tucker [MVP]

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???
 
G

Guest

Fine solution, provided you know the index is 4...

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

-Zorpy
 
Joined
Sep 27, 2006
Messages
1
Reaction score
0
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
 
Joined
Aug 17, 2014
Messages
1
Reaction score
0
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top