Programmatically Checking DataBound CheckListBox

后端 未结 1 769
無奈伤痛
無奈伤痛 2021-01-25 05:37

I have a DataBound \"CheckedListBox\", I need to check some items on it. I tried with following code...

if (!string.IsNullOrEmpty(search.Languages))
        {
           


        
相关标签:
1条回答
  • 2021-01-25 06:07

    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...

    0 讨论(0)
提交回复
热议问题