Results 1 to 2 of 2

Thread: check listbox

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2007
    Posts
    694

    check listbox

    I am populating a check list box from the database as follows:

    for (int i = 0; i < intClassID; i++)
    {
    strClassID = dtClass.Rows[i]["ClassID"].ToString();
    strName = dtClass.Rows[i]["Name"].ToString();

    chklstClass.Items.Add(new ListItem(strName, strClassID));
    }

    So each item in the listbox has an ID

    Now I would like to retrieve so that the IDs are selected approprioately. This is what I do:

    for (int i = 0; i <= dtClass.Rows.Count - 1; i++)
    {
    int intClassID = int.Parse(dtClass.Rows[i][0].ToString());
    chklstClass.Items[intClassID].Selected = true;
    }

    It does not seem to get the proper ID's
    What am I doing wrong?
    is this to do with SetItemChecked(i, true) ?

    Thanks

  2. #2
    Addicted Member
    Join Date
    Nov 2006
    Location
    Minnesota
    Posts
    235

    Re: check listbox

    You won't get the proper ID's. You are comparing the ClassID which you have set to the value, to the index within the list -- they aren't comparable in this context. What you need to do is in the second for loop, find the index of the value within the list, then mark it selected.

    Code:
     for (int i = 0; i < intClassID; i++)
            {
                strClassID = dtClass.Rows[i]["ClassID"].ToString();
                strName = dtClass.Rows[i]["Name"].ToString();
                chklstClass.Items.Add(new ListItem(strName, strClassID));
            }
            
            for (int i = 0; i <= dtClass.Rows.Count - 1; i++)
            {
                //int intClassID = int.Parse(dtClass.Rows[i][0].ToString());
                //chklstClass.Items[intClassID].Selected = true;
                chklstClass.Items[chklstClass.Items.FindByValue(dtClass.Rows[i][0].ToString())].Selected = true;
            }
    If someone has helped you, please make sure to rate them.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width