问题
I have a DataBound "CheckedListBox", I need to check some items on it. I tried with following code...
if (!string.IsNullOrEmpty(search.Languages))
{
string[] langs = search.Languages.Split(',');
for (int i = 0; i < (langs.Length - 1); i++)
{
for (int j = 0; j < clbLang.Items.Count; j++)
{
string lng = clbLang.Items[j] as string;
if (lng.Trim() == langs[i])
{
clbLang.SetItemChecked(j, true);
break;
}
}
}
}
No errors, debuged execution is going through "checking" process, but finally I cannot see anything checked on it.
Then I have added a button and added following code to it. (upon click check all the items)
private void button9_Click(object sender, EventArgs e)
{
for (int i = 0; i < clbLang.Items.Count; i++)
{
clbLang.SetItemChecked(i, true);
}
}
It is "checking" all the items, Please tell me if anyone can see a issue here...?
回答1:
Finally found out, it is a Bug introduced by MS.
It is well explained here.
The issue is easy to reproduce. Just hide and show a databound CheckedListBox and you will notice how the previously checked items get unchecked.
CheckedListBox SetItemChecked method not working
So we have to find a workaround... I tried follwing way, it is working nice...
At the place where I was calling checking of items I have added following... I am adding what I need to check in Tag of the control.
if (!string.IsNullOrEmpty(search.Languages))
{
clbLang.Tag = search.Languages;
}
Then, following code in that control's "VisibleChanged()" event.
private void clbLang_VisibleChanged(object sender, EventArgs e)
{
string lngs = clbLang.Tag as string;
if (!string.IsNullOrEmpty(lngs))
{
string[] langs = lngs.Split(',');
foreach (string lang in langs)
{
int j = 0;
foreach (DataRowView row in clbLang.Items)
{
if (row != null)
{
string lng = row[1] as string;
if (lng.Trim() == lang)
{
clbLang.SetItemChecked(j, true);
break;
}
}
j++;
}
}
}
}
This works well with me, hope it will benefit you...
来源:https://stackoverflow.com/questions/4654056/programmatically-checking-databound-checklistbox