-
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
-
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;
}