How to get value of checked item from CheckedListBox?
Asked Answered
C

9

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.

Cracow answered 2/2, 2011 at 14:25 Comment(1)
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 shares a general solution.Xenogenesis
C
41

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"];
}
Cleancut answered 2/2, 2011 at 14:40 Comment(5)
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.Cracow
@w69rdy: The CheckedItems property is an array of objects. An object doesn't have a SelectedValue property, they can be anything.Ifni
@w69rdy: I am getting castedItem as null.Cracow
@w69rdy: I found the solution. I just replaced DataRow with DataRowView. Its now working. Can you please update your solution.Cracow
@w69rdy: Please update your answer changing DataRow with DataRowView. Its working now. I am accepting your solution.Cracow
C
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);
}
Chacon answered 2/2, 2011 at 14:44 Comment(0)
I
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

Ifni answered 2/2, 2011 at 14:31 Comment(2)
Thanks Evan! But my question is how to get the associate ID of the checked item?Cracow
@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.Ifni
V
2
foreach (int x in chklstTerms.CheckedIndices)
{
    chklstTerms.SelectedIndex=x;
    termids.Add(chklstTerms.SelectedValue.ToString());
}
Vitrification answered 16/3, 2012 at 7:8 Comment(0)
F
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());

    }

}
Fissi answered 12/2, 2018 at 11:13 Comment(0)
T
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.

Trampoline answered 19/9, 2011 at 13:50 Comment(0)
X
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.

Xenogenesis answered 16/5, 2019 at 17:55 Comment(0)
D
-1

try:

  foreach (var item in chlCompanies.CheckedItems){
     item.Value //ID
     item.Text //CompanyName
  }
Diffusion answered 20/8, 2015 at 19:1 Comment(1)
you should add a little description of what the code does. You are also missing semi-colons in your code.Anteater
F
-2

You may try this :

string s = "";

foreach(DataRowView drv in checkedListBox1.CheckedItems)
{
    s += drv[0].ToString()+",";
}
s=s.TrimEnd(',');
Fortis answered 6/4, 2011 at 14:37 Comment(1)
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.Panettone

© 2022 - 2024 — McMap. All rights reserved.