How to get value of checked item from CheckedListBox? - c#

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.

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);
}

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

foreach (int x in chklstTerms.CheckedIndices)
{
chklstTerms.SelectedIndex=x;
termids.Add(chklstTerms.SelectedValue.ToString());
}

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());
}
}

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.

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.

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

You may try this :
string s = "";
foreach(DataRowView drv in checkedListBox1.CheckedItems)
{
s += drv[0].ToString()+",";
}
s=s.TrimEnd(',');

Related

How to set Selectedvalue in Combobox c#

I have one combobox in which I have set DataSource Value, but when I try to set SelectedValue, the ComboBox returns null. so please help.
BindingList<KeyValuePair<string, int>> m_items =
new BindingList<KeyValuePair<string, int>>();
for (int i = 2; i <= 12; i++)
m_items.Add(new KeyValuePair<string, int>(i.ToString(), i));
ComboBox cboGridSize = new ComboBox();
cboGridSize.DisplayMember = "Key";
cboGridSize.ValueMember = "Value";
cboGridSize.DataSource = m_items;
cboGridSize.SelectedValue = 4;
when I set SelectedValue with 4 then it returns NULL.
Agree with #Laazo change to string.
cboGridSize.SelectedValue = "4";
or somthing similar to this
int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;
MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
"Index: " + selectedIndex.ToString());
and refer to this looks as if it would be good for your issue:
https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selecteditem(v=vs.110).aspx
How do I set the selected item in a comboBox to match my string using C#?
Getting selected value of a combobox
I came across this question while also trying to solve this problem. I solved it by creating the following extension method.
public static void ChooseItem<T>(this ComboBox cb, int id) where T : IDatabaseTableClass
{
// In order for this to work, the item you are searching for must implement IDatabaseTableClass so that this method knows for sure
// that there will be an ID for the comparison.
/* Enumerating over the combo box items is the only way to set the selected item.
* We loop over the items until we find the item that matches. If we find a match,
* we use the matched item's index to select the same item from the combo box.*/
foreach (T item in cb.Items)
{
if (item.ID == id)
{
cb.SelectedIndex = cb.Items.IndexOf(item);
}
}
}
I also created an interface called IDatabaseTableClass (probably not the best name). This interface has one property, int ID { get; set; } To ensure that we actually have an ID to compare to the int id from the parameter.

How to retrieve selected values for selected items in a ListBox?

I'm populating a ListBox in a WinForms application, this way:
listBoxUsers.DataSource = ctx.Users.ToList();
listBoxUsers.DisplayMember = "Name";
listBoxUsers.ValueMember = "Id";
how to retrieve the selected Ids when I'm setting the SelectionMode to MultiSimple
I want to do a foreach loop on them, like this:
foreach(var itemId in listBoxUsers.SelectedValues)//unfortunately not exist
{
int id = int.Parse(itemId);
// . . .
}
Since you know the type of items, you can use such code:
var selectedValues = listBox1.SelectedItems.Cast<User>().Select(x=>x.Id).ToList();
Side Note: The ListBox control lacks a GetItemValue method. A method which should work like GetItemText, but for getting values. In the linked post I shared an extension method to get the value from an item. Using that extension method you can get selected values independent from type of items:
var selectedValues = listBox1.SelectedItems.Cast<object>()
.Select(x => listBox1.GetItemValue(x)).ToList();
If for some reason you are interested to have a text representation for selected values:
var txt = string.Join(",", selectedValues);
Have you tried with the SelectedItems property?
foreach (var item in listBoxUsers.SelectedItems)
{
}
try this:
foreach (DataRowView item in listBoxUsers.SelectedItems)
{
int id=int.parse(item[0].ToString());
}

Getting the value and items in checkListBox

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+"'
}
You can try like this:
foreach(object item in checkListBox.CheckedItems)
{
DataRowView dt = item as DataRowView;
string str = dt["nameHere"];
// some code
}
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
}
You can try this
foreach(var item in checkListBox.CheckedItems){
var value = (item as ListItem).Value;
}
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() + "';
}
}
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 +")

Store elements from a ListView into a List

Since I haven't found anything that helped, I ask my question here:
I have a ListView where I select a whole row by click. Now I want to store these selected items into a List but don't know how this should work exactly.
List<String> itemSelected = new List<String>();
foreach (var selectedRow in listView1.SelectedItems)
{
itemSelected.Add(selectedRow);
}
That doesn't work because I need an index (selectedRow[?]) or something like that. How can I store the values of the first column when clicked the row?
EDIT: The problem is that the ListViewItems have the type "object"
The ListView gets populated this way:
using (SqlConnection connection = new SqlConnection(connectionQuery))
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
col1 = row.Cells[col1.Text].Value.ToString();
col2 = row.Cells[col2.Text].Value.ToString();
col1Cells.Add(col1);
col2Cells.Add(col2);
}
}
You can do something like:
ListViewItem listViewItem = this.listView1.SelectedItems.Cast<ListViewItem>().FirstOrDefault();
if (listViewItem != null)
{
string firstColumn = listViewItem.Text;
string secondColumn = listViewItem.SubItems[0].Text;
// and so on with the SubItems
}
If you have more selected items and only need the values of the first columns you can use:
List<string> values = listView1.SelectedItems.Cast<ListViewItem>().Select(listViewItem => listViewItem.Text).ToList();
It's common to bind a ListView to the List of non-trivial types.
Then you can handle SelectedItemChanged or something like that. You receive the whole object (in type object) which you can cast to your custom type and retrieve any properties you want

how to get DisplayMemeber value from listbox by valuemember c#?

I have a listBox, something like this:
ID ClientName
Michael
Steve
Smith
Now, I know the ID of the client , how do i get the DisplayMember of it ?
Cast into DataRowView and convert select the client name column by index, which is 1.
String ClientName = (((DataRowView) listBox1.SelectedItem).Row[1]).ToString();
You could try this code. the example is written if the DataSource of the Listbox is DataTable, but if it is something else, try to see of what type is the object in Items property of the ListBox.
(Note that I don't like using break statement but this was the quickest way)
string str = string.Empty;
foreach (DataRowView drv in listBox1.Items)
{
int lvID = int.Parse(drv.Row[listBox1.ValueMember].ToString());
if (lvID == 5)
{
str = drv.Row[listBox1.DisplayMember].ToString();
break;
}
}
var t = from list in USStates where te.ShortName == textBox1.Text select te.LongName.ToString();
foreach(String st in t)
{
MessageBox.Show(st);
}
where USStates is Generic List and TextBox1.text contains the value of the id.Considering your listbox uses Generic list as DataSource.
There is a much easier solution. Especially if you are building the DataSource, populating it, then releasing the source. Use the Items list to create a DataRowView of the item currently selected. Then just pull the right index. 0 will give you the "value member" and 1 will give you the "display member".
DataRowView thisLine = cbTrackerFormList.Items[cbTrackerFormList.SelectedIndex] as DataRowView;

Categories

Resources