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 +")
Related
I have two indexes on my combobox.
I want to take only the first index ?
Can I get some example ?
The code:
foreach (DataRow dr2 in dt2.Rows)
{
comboBox1.Items.Add(dr2["Station"].ToString() + " - " + dr2["Ime"].ToString());
}
I want to take dr2["Station"].ToString() ?
The Win Forms ComboBox has both a SelectedIndex and SelectedText property.
Once your list is loaded with items you can pick which one is selected like this:
// selected by position in the list
comboBox1.SelectedIndex = 0;
// ... by value
comboBox1.SelectedText = "some value";
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.
i have a drop down list on my page with Countries, here is my code behind where i grab the ddl id, and bind my datasource:
DropDownList ddlSalary = (DropDownList)this.FindControl(MyControls.CountryDDL);
if (ddlSalary != null)
{
ddlSalary.DataSource = MyMethods.LoadCountries();
ddlSalary.DataValueField = "Value";
ddlSalary.DataTextField = "Text";
ddlSalary.DataBind();
}
My Countries ive written in are Alphabetical. But id like the option to move a specific one to the top of the List, or perhaps an Auto-Select. Example 'United Kingdom' is first in the list
What would be the most efficient way to go about doing this ?
I think this logic is better suited to be placed in your service/model provider (MyMethods.LoadCountries(); ).
Something like:
public static List<Country> LoadOrderedCountries(){
var orderedCounteries = MyMethods.LoadCountries();
orderedCounteries .Sort(); // Just to make sure alphabetical order, assuming that Country implements IComparable
var defaultCountry = Country.GetDefault();
orderedCounteries .Remove(defaultCountry);
orderedCounteries .Insert(0, defaultCountry);
return orderedCounteries ;
}
Here is a quick & dirty way to do it with SQL. I prefer to do it at database level
What I am doing is selecting the items you want first in the list
Union ALL with items you want in the list in ascending order by name excluding the ones in my first query
Results are with first Item at top irrespective of 2nd query
select * from ( (select Empcode,Empname from
mySchema.Employees where EmpCode not in (90) ) UNION ALL
select EmpCode,EmpName from mySchema.Employeeswhere
EmpCode=90 order by EmpName) as z
You ca also set the value selected on pageLoad as
ddlYourDropDownList.SelectedValue="90";
After databinding your datasource, you can just sort the ListItems
A better way to do so is to do the sorting in your datasource (you haven't supplied enough information regarding where are you getting the data from)
private void SortDDL(ref DropDownList objDDL)
{
ArrayList textList = new ArrayList();
ArrayList valueList = new ArrayList();
foreach (ListItem li in objDDL.Items)
{
textList.Add(li.Text);
}
textList.Sort();
foreach (object item in textList)
{
string value = objDDL.Items.FindByText(item.ToString()).Value;
valueList.Add(value);
}
objDDL.Items.Clear();
for(int i = 0; i < textList.Count; i++)
{
ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());
objDDL.Items.Add(objItem);
}
}
I normally do this in the databound event
DropDownList ddlSalary = (DropDownList)this.FindControl(MyControls.CountryDDL);
if (ddlSalary != null)
{
ddlSalary.DataSource = MyMethods.LoadCountries();
ddlSalary.DataValueField = "Value";
ddlSalary.DataTextField = "Text";
ddlSalary.DataBind();
ddlSalary.DataBound += ddlSalary_DataBound;
}
protected void ddlSalary_DataBound(object sender, EventArgs e)
{
ListItem MovingItem = ddlSalary.Items.FindByValue("yourvalue");
ddlSalary.Items.Remove(MovingItem);
ddlSalary.Items.Insert(0, MovingItem);
}
Edit: this method is more suited to adding an a "Other" type option, which is not supplied by your datasource. Amby's solution is better than this.
I have a CheckedListBox bound to a DataTable. Now I need to check some items programmatically, but I find that the SetItemChecked(...) method only accepts the item index.
Is there a practical way to get an item by text/label, without knowing the item index?
(NOTE: I've got limited experience with WinForms...)
You can implement your own SetItemChecked(string item);
private void SetItemChecked(string item)
{
int index = GetItemIndex(item);
if (index < 0) return;
myCheckedListBox.SetItemChecked(index, true);
}
private int GetItemIndex(string item)
{
int index = 0;
foreach (object o in myCheckedListBox.Items)
{
if (item == o.ToString())
{
return index;
}
index++;
}
return -1;
}
The checkListBox uses object.ToString() to show items in the list. You you can implement a method that search across all objects.ToString() to get an item index. Once you have the item index, you can call SetItemChecked(int, bool);
Hope it helps.
You may try to browse your Datatable. YOu can do a foreach on the DataTabke.Rows property or use SQL syntax as below:
DataTable dtTable = ...
DataRow[] drMatchingItems = dtTable.Select("label = 'plop' OR label like '%ploup%'"); // I assumed there is a "label" column in your table
int itemPos = drMatchingItems[0][id]; // take first item, TODO: do some checking of the length/matching rows
Cheers,
I am answering it very late, I hope it will help someone. If you want to find any item by name we can do it in two steps. First get index of item by text and then we can get actual item with the help of index.
var selectedItemIndex = cbxList.Items.IndexOf("sometext");
var selectedItem = cbxList.Items[selectedItemIndex];
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(',');