开发者

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 datab开发者_运维百科ound items instead of using lstInstructors.Items?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜