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+"'

}

Solutions1

You can try like this:

foreach(object item in checkListBox.CheckedItems)

{

DataRowView dt = item as DataRowView;

string str = dt["nameHere"];

// some code

}

Talk1:

can I do this with sql query?

Talk2:

:- I don't think it would be a good idea to do it using sql query.

Talk3:

I see. thanks for your suggestion. I will give it a try

Talk4:

:- If you can bind the result of your sql query to a DataTable then you can cast it to a DataRowView and then take its Row property to get a DataRow.

Solutions2

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

}

Solutions3

You can try this

foreach(var item in checkListBox.CheckedItems){

var value = (item as ListItem).Value;

}

Talk1:

Hi Roy, I can only find ListViewItem though

Solutions4

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() + "';

}

}

Solutions5

You can do it other way as well

List _checkedItems = checkedListBox1.CheckedItems.OfType().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 +")

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐