Reputation: 1733
I am writing a Windows Forms application that has a checkListBox. I have a databinded checkListBox value that is connected to my sql db. I want to write a loop to loop through a list of checked items and get its value (not index). I am wondering is there a way to do it just like the comboBox.SelectedValue?
foreach(var item in checkListBox.CheckedItems){
//get the value of that
string query = select * from employeeId where '"+checkListBox.SelectedValue+"'
}
Upvotes: 1
Views: 100
Reputation: 10296
You can do it other way as well
List<object> _checkedItems = checkedListBox1.CheckedItems.OfType<object>().ToList();
This will give you all the checked items. If you want to pass this into sql query then you can do something like
string delimeter = "','";
string _selectedItems ="'"+ _checkedItems.Aggregate((i, j) => i + delimeter + j).ToString()+"'";
and pass it in your sql query
string query = select * from employeeId where somevalue in ("+_selectedItems +")
Upvotes: 0
Reputation: 14064
The items in the CheckedListBox
and checks every other item in the list. Using the Items property to get the CheckedListBox.ObjectCollection to get the Count of items.
Using the SetItemCheckState
and SetItemChecked
methods to set the check state of an item. For every other item that is to be checked, SetItemCheckState is called to set the CheckState to Indeterminate, while SetItemChecked is called on the other item to set the checked state to Checked.
//checkedListBox1.SetItemChecked(a,true);
for ( int i = 0; i < checkedListBox1.Items.Count; i++ )
{
if(checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
string query = select * from employeeId where '" + checkedListBox1.Items[i].ToString() + "';
}
}
Upvotes: 0
Reputation: 69
You can try this
foreach(var item in checkListBox.CheckedItems){
var value = (item as ListItem).Value;
}
Upvotes: 0
Reputation: 172628
You can try like this:
foreach(object item in checkListBox.CheckedItems)
{
DataRowView dt = item as DataRowView;
string str = dt["nameHere"];
// some code
}
Upvotes: 1
Reputation: 1564
You should cast the item to the relevant type (DataRowView?)
foreach(var item in checkListBox.CheckedItems){
var val = item as DataRowView;
// retrieving the relevant values
}
Upvotes: 0