How to get value of checked item from CheckedListBox?
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
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"];
}
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);
}