32

I have used a CheckedListBox over my WinForm in C#. I have bounded this control as shown below -

chlCompanies.DataSource = dsCompanies.Tables[0];
chlCompanies.DisplayMember = "CompanyName";
chlCompanies.ValueMember = "ID";

I can get the indices of checked items, but how can i get checked item text and value. Rather how can i enumerate through CheckedItems accessing Text and Value?

Thanks for sharing your time.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
IrfanRaza
  • 3,030
  • 17
  • 64
  • 89
  • The underlying `Value` of an item should be calculated regarding to `ValueMember`, regardless of the type of data source. The data source may be a `DataTable` or a `List` and the type of the item may be `DataRowView` or `object` or simple data types. [This post](https://stackoverflow.com/a/56174135/3110834) shares a general solution. – Reza Aghaei May 16 '19 at 18:08

9 Answers9

40

Cast it back to its original type, which will be a DataRowView if you're binding a table, and you can then get the Id and Text from the appropriate columns:

foreach(object itemChecked in checkedListBox1.CheckedItems)
{
     DataRowView castedItem = itemChecked as DataRowView;
     string comapnyName = castedItem["CompanyName"];
     int? id = castedItem["ID"];
}
Iain Ward
  • 9,850
  • 5
  • 34
  • 41
  • My friend, I think you have not gone thoroughly with my question. I am using CheckedListBox. I dont need any selection, instead i want checked items. The property just gives the value of selected item only. – IrfanRaza Feb 02 '11 at 14:43
  • @w69rdy: The `CheckedItems` property is an array of `objects`. An `object` doesn't have a `SelectedValue` property, they can be anything. – Evan Mulawski Feb 02 '11 at 14:51
  • @w69rdy: I am getting castedItem as null. – IrfanRaza Feb 02 '11 at 14:59
  • @w69rdy: I found the solution. I just replaced DataRow with DataRowView. Its now working. Can you please update your solution. – IrfanRaza Feb 02 '11 at 15:01
  • @w69rdy: Please update your answer changing DataRow with DataRowView. Its working now. I am accepting your solution. – IrfanRaza Feb 02 '11 at 15:05
14

EDIT: I realized a little late that it was bound to a DataTable. In that case the idea is the same, and you can cast to a DataRowView then take its Row property to get a DataRow if you want to work with that class.

foreach (var item in checkedListBox1.CheckedItems)
{
    var row = (item as DataRowView).Row;
    MessageBox.Show(row["ID"] + ": " + row["CompanyName"]);
}

You would need to cast or parse the items to their strongly typed equivalents, or use the System.Data.DataSetExtensions namespace to use the DataRowExtensions.Field method demonstrated below:

foreach (var item in checkedListBox1.CheckedItems)
{
    var row = (item as DataRowView).Row;
    int id = row.Field<int>("ID");
    string name = row.Field<string>("CompanyName");
    MessageBox.Show(id + ": " + name);
}

You need to cast the item to access the properties of your class.

foreach (var item in checkedListBox1.CheckedItems)
{
    var company = (Company)item;
    MessageBox.Show(company.Id + ": " + company.CompanyName);
}

Alternately, you could use the OfType extension method to get strongly typed results back without explicitly casting within the loop:

foreach (var item in checkedListBox1.CheckedItems.OfType<Company>())
{
    MessageBox.Show(item.Id + ": " + item.CompanyName);
}
Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
11

You can iterate over the CheckedItems property:

foreach(object itemChecked in checkedListBox1.CheckedItems)
{
    MyCompanyClass company = (MyCompanyClass)itemChecked;    
    MessageBox.Show("ID: \"" + company.ID.ToString());
}

http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.checkeditems.aspx

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
  • Thanks Evan! But my question is how to get the associate ID of the checked item? – IrfanRaza Feb 02 '11 at 14:37
  • @IrfanRaza: See my edited code sample. You would need to cast each item that was checked to your custom data type to access its specific properties. – Evan Mulawski Feb 02 '11 at 14:50
2
foreach (int x in chklstTerms.CheckedIndices)
{
    chklstTerms.SelectedIndex=x;
    termids.Add(chklstTerms.SelectedValue.ToString());
}
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
1

To get the all selected Items in a CheckedListBox try this:

In this case ths value is a String but it's run with other type of Object:

for (int i = 0; i < myCheckedListBox.Items.Count; i++)
{
    if (myCheckedListBox.GetItemChecked(i) == true)
    {

        MessageBox.Show("This is the value of ceckhed Item " + myCheckedListBox.Items[i].ToString());

    }

}
daniele3004
  • 13,072
  • 12
  • 67
  • 75
0

I've already posted GetItemValue extension method in this post Get the value for a listbox item by index. This extension method will work for all ListControl classes including CheckedListBox, ListBox and ComboBox.


None of the existing answers are general enough, but there is a general solution for the problem.

In all cases, the underlying Value of an item should be calculated regarding to ValueMember, regardless of the type of data source.

The data source of the CheckedListBox may be a DataTable or it may be a list which contains objects, like a List<T>, so the items of a CheckedListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types.

GetItemValue Extension Method

We need a GetItemValue which works similar to GetItemText, but return an object, the underlying value of an item, regardless of the type of object you added as item.

We can create GetItemValue extension method to get item value which works like GetItemText:

using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
    public static object GetItemValue(this ListControl list, object item)
    {
        if (item == null)
            throw new ArgumentNullException("item");

        if (string.IsNullOrEmpty(list.ValueMember))
            return item;

        var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
        if (property == null)
            throw new ArgumentException(
                string.Format("item doesn't contain '{0}' property or column.",
                list.ValueMember));
        return property.GetValue(item);
    }
}

Using above method you don't need to worry about settings of ListBox and it will return expected Value for an item. It works with List<T>, Array, ArrayList, DataTable, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:

//Gets underlying value at index 2 based on settings
this.checkedListBox.GetItemValue(this.checkedListBox.Items[2]);

Since we created the GetItemValue method as an extension method, when you want to use the method, don't forget to include the namespace in which you put the class.

This method is applicable on ComboBox and CheckedListBox too.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
0

Egypt Development Blog : Get value of checked item in CheckedListBox in vb.net

after bind CheckedListBox with data you can get value of checked items

For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
                    Dim XDRV As DataRowView = CType(CheckedListBox1.CheckedItems(i), DataRowView)
                    Dim XDR As DataRow = XDRV.Row
                    Dim XDisplayMember As String = XDR(CheckedListBox1.DisplayMember).ToString()
                    Dim XValueMember As String = XDR(CheckedListBox1.ValueMember).ToString()
                    MsgBox("DisplayMember : " & XDisplayMember & "   - ValueMember : " & XValueMember )
Next

now you can use the value or Display of checked items in CheckedListBox from the 2 variable XDisplayMember And XValueMember in the loop

hope to be useful.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
-1

try:

  foreach (var item in chlCompanies.CheckedItems){
     item.Value //ID
     item.Text //CompanyName
  }
-2

You may try this :

string s = "";

foreach(DataRowView drv in checkedListBox1.CheckedItems)
{
    s += drv[0].ToString()+",";
}
s=s.TrimEnd(',');
Chris Salij
  • 3,096
  • 5
  • 26
  • 43
  • Welcome to SO, Madhuchhanda. How is your answer substantively different from the other answers already provided? Best not to provide duplicate answers as it merely adds to the noise and makes it more confusing for people seeking help. – Kirk Woll Apr 06 '11 at 14:54