Joey
Joey

Reputation: 535

Iterate through databound listbox

My listbox is getting its items from a sql database and I'm trying to loop through it and perform an action based on a certain condition. I've done this before but not when it was attached to a db. This is the code I'm using (that doesnt work):

foreach (object o in arrList)
{
    foreach (ListItem i in lstInstructors.Items)
    {
        if (i.Text == o.ToString())
        i.Selected = true;
    }
}

While I'm debugging im getting null as ListItem i, and I'm guessing thats because there's no static items added, so what would be the right call to get the databound items instead of using lstInstructors.Items?

Upvotes: 1

Views: 1921

Answers (1)

Matthew Jones
Matthew Jones

Reputation: 26190

Make sure you are doing this in the DataBound event:

protected void lstInstructors_DataBound(object sender, EventArgs e)
{
    foreach (object o in arrList)
    {
        foreach (ListItem i in lstInstructors.Items)
        {
            if (i.Text == o.ToString())
                i.Selected = true;
        }
    }
}

This will ensure that any items that need to be bound are in fact bound when the method runs.

Upvotes: 1

Related Questions