Link to home
Start Free TrialLog in
Avatar of gladstonesheeba
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.SelectedItem.Text = s.ToString();   ---Getting Error in this line
                   }


Please help me out in this. Thanks
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

is your listbox bound to a datasource? if so, it should be:
TheaterListbox.SelectedValue = s.ToString();  

if not, it should be something like:
TheaterListbox.SelectedItem = s.ToString();  
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
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;
}

Open in new window

Avatar of Toms Edison
try this code

foreach (string s in Theatres)
                   {
                       TheaterListbox.Items.FindByText(s.ToString()).Selected = true;
                   }
Avatar of gladstonesheeba
gladstonesheeba

ASKER

I tried what you mentioned Theaterlistbox.selecteditem=s.tostring(); I gave me two errors. please look in to this.

Error      5      Property or indexer 'System.Web.UI.WebControls.ListControl.SelectedItem' cannot be assigned to -- it is read only      

Error      6      Cannot implicitly convert type 'string' to 'System.Web.UI.WebControls.ListItem'      
ASKER CERTIFIED SOLUTION
Avatar of jinn_hnnl
jinn_hnnl
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Have you try my 2nd post, the added solution? Is that you want to add these List<string> values to your ListBox
Excellent, Thanks for your help
gladstonesheeba, unless you first try the examples we have provided, there is no point to discus further.