gladstonesheeba
asked on
error with listbox selection
I have a listbox on my webform populated values from the database table. i have a List<string> variable contains some values. i need to get the strings from list<string> variable and select those strings in the Listbox.
Here's the code i tried, but it gives me a error as object reference not set to an instance of the object.
foreach (string s in Theatres)
{
TheaterListbox.SelectedIte m.Text = s.ToString(); ---Getting Error in this line
}
Please help me out in this. Thanks
Here's the code i tried, but it gives me a error as object reference not set to an instance of the object.
foreach (string s in Theatres)
{
TheaterListbox.SelectedIte
}
Please help me out in this. Thanks
What type of error do you have.
What you do is like you set the selected item for your listBox which only valid when: your listBox has already contain list of items, and you whan one of them to be selected.
So the code you gave is not quite right.
I think you will have to add them instead of set the selected property
foreach (string s in Theatres)
{
myList.Items.Add(new ListItem(s, s));
}
Hope this helps
What you do is like you set the selected item for your listBox which only valid when: your listBox has already contain list of items, and you whan one of them to be selected.
So the code you gave is not quite right.
I think you will have to add them instead of set the selected property
foreach (string s in Theatres)
{
myList.Items.Add(new ListItem(s, s));
}
Hope this helps
if its a multiselection then you will need to do this
ListBox1.ClearSelection();
foreach (string s in Theatres)
{
ListItem item = ListBox1.Items.FindByText(s);
if (item != null) item.Selected = true;
}
try this code
foreach (string s in Theatres)
{
TheaterListbox.Items.FindB yText(s.To String()). Selected = true;
}
foreach (string s in Theatres)
{
TheaterListbox.Items.FindB
}
ASKER
I tried what you mentioned Theaterlistbox.selectedite m=s.tostri ng(); I gave me two errors. please look in to this.
Error 5 Property or indexer 'System.Web.UI.WebControls .ListContr ol.Selecte dItem' cannot be assigned to -- it is read only
Error 6 Cannot implicitly convert type 'string' to 'System.Web.UI.WebControls .ListItem'
Error 5 Property or indexer 'System.Web.UI.WebControls
Error 6 Cannot implicitly convert type 'string' to 'System.Web.UI.WebControls
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Have you try my 2nd post, the added solution? Is that you want to add these List<string> values to your ListBox
ASKER
Excellent, Thanks for your help
gladstonesheeba, unless you first try the examples we have provided, there is no point to discus further.
TheaterListbox.SelectedVal
if not, it should be something like:
TheaterListbox.SelectedIte