How to retrieve texts for CheckedItems in CheckedListBox

Durgesh Pandey picture Durgesh Pandey · Jun 10, 2016 · Viewed 11.3k times · Source

I have a CheckBoxList which contain dynamic data.Now i want to get the list of selected item from CheckBoxList. i am using following code.

for (int i = 0; i < chkTblListDb001.Items.Count; i++)
{
    if (chkTblListDb001.GetItemChecked(i))
    {
          FirstTableSelectedColumns += chkTblListDb001.Items[i].ToString() + ",";
          MessageBox.Show(FirstTableSelectedColumns);
    }
}

but is return (in FirstTableSelectedColumns variable) "System.Data.DataRowView,System.Data.DataRowView,"

When I am using the this code

string test = "you've selected :";

foreach (ListItem item in theCheckBoxList.Items)
{
    test += item.Selected ? item.Value + ", " : "";
}
labelResult.Text = test;

its give me the following error that

ListItem not found.

Answer

Reza Aghaei picture Reza Aghaei · Jun 10, 2016

To get text of an item in CheckedListBox you can use GetItemText.

It doesn't matter what is the type of item, if you have used DataSource and DisplayMember it uses DisplayMember to return text, otherwise it uses ToString method of item.

Here is an example of what you are looking for, a comma-separated list of checked item texts:

var texts = this.checkedListBox1.CheckedItems.Cast<object>()
                .Select(x => this.checkedListBox1.GetItemText(x));

MessageBox.Show(string.Join(",", texts));