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.
Related
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 +")
i am using CheckedListBox so that user can multi select items for this i am populating CheckedListBox dynamically from database Here is CheckedListBox Filling Method
public void FillSubjectsCombo()
{
DataTable dt = objSubCls.FillSubjects();
chkLstBxClass_FrmSubjecClassRelation.DataSource = dt;
chkLstBxClass_FrmSubjecClassRelation.DisplayMember = "Subjects";
chkLstBxClass_FrmSubjecClassRelation.ValueMember = "SubId";
chkLstBxClass_FrmSubjecClassRelation.Enabled = true;
for (int i = 0; i < dt.Rows.Count; i++)
{
//Here i am setting Every item Checked
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(i, CheckState.Checked);
}
}
On the Same Windows Form I have DataGridView i Want when i double click any row of datagrid then from selected row get value and from that value make respected item checked in CheckedListBox and other item UnChecked
Here is the DataGridView Event
private void dgv_FrmSubjectClassRelation_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
string classId = dgv_FrmSubjectClassRelation.CurrentRow.Cells[3].Value.ToString();
string className = dgv_FrmSubjectClassRelation.CurrentRow.Cells[4].Value.ToString();
foreach (int i in chkLstBxClass_FrmSubjecClassRelation.CheckedIndices)
{
//Here I am UnChecking Every Checked Item
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(i, CheckState.Unchecked);
}
My Question : How to Checked The Specific Item When Double Clicking DataGridView
Update: I am binding My DataGridView Like This
for (int i = 0; i < dt.Rows.Count; i++)
{
dgv_FrmSmstrClsAssign.Rows.Add();
dgv_FrmSmstrClsAssign.Rows[i].Cells[0].Value = dt.Rows[i].ItemArray[0];//Acadmc Yr
dgv_FrmSmstrClsAssign.Rows[i].Cells[1].Value = dt.Rows[i].ItemArray[1];// Semester Name
dgv_FrmSmstrClsAssign.Rows[i].Cells[2].Value = dt.Rows[i].ItemArray[2]; //College
dgv_FrmSmstrClsAssign.Rows[i].Cells[3].Value = dt.Rows[i].ItemArray[3];//Class
dgv_FrmSmstrClsAssign.Rows[i].Cells[4].Value = dt.Rows[i].ItemArray[4]; //Entry Date
dgv_FrmSmstrClsAssign.Rows[i].Cells[5].Value = dt.Rows[i].ItemArray[5];//IsActive
dgv_FrmSmstrClsAssign.Rows[i].Cells[6].Value = dt.Rows[i].ItemArray[6];//AcadmicYr Id
dgv_FrmSmstrClsAssign.Rows[i].Cells[7].Value = dt.Rows[i].ItemArray[7];//Semster Id
dgv_FrmSmstrClsAssign.Rows[i].Cells[8].Value = dt.Rows[i].ItemArray[8];//Semster Id
}
I was unable to find any method that allows you to easily map the bound value, so you will have to use IndexOf method of Items collection to obtain the index and then manually check-uncheck the items.
To obtain the bound item from DataGridView row you can use DataGridViewRow.DataBoundItem property:
private void CheckSelectedItem()
{
// Get bound item object from datagrid
object item = dgv_FrmSubjectClassRelation.CurrentRow.DataBoundItem;
// Get corresponding index in listView
Int32 itemIndexInCheckedListView = chkLstBxClass_FrmSubjecClassRelation.Items.IndexOf(item);
// Check the item in listView
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(itemIndexInCheckedListView,
CheckState.Checked);
}
private void dgv_FrmSubjectClassRelation_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
string classId = dgv_FrmSubjectClassRelation.CurrentRow.Cells[3].Value.ToString();
string className = dgv_FrmSubjectClassRelation.CurrentRow.Cells[4].Value.ToString();
foreach (int i in chkLstBxClass_FrmSubjecClassRelation.CheckedIndices)
{
//Here I am UnChecking Every Checked Item
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(i, CheckState.Unchecked);
}
// --------------Check the selected item----------------
this.CheckSelectedItem();
}
EDIT:
What you do is not exactly binding (well, it is binding, just not as Windows Forms defines it), so the previous solution won't work for you. If both your DataTable and DataGridView contain primary key or another unique identifier, then it is possible to map CurrentRow to the Item in DataTable:
private void CheckSelectedItem()
{
// Get bound item object from datagrid
object uniqueKey = dgv_FrmSubjectClassRelation.
CurrentRow.
Cells["SOME UNIQUE VALUE COLUMN"].
Value;
// Adapting http://stackoverflow.com/a/9300237/3745022 - there are more simple LINQless
// solutions for this situation, but it is not important for the concept.
Int32 itemIndexInCheckedListView = chkLstBxClass_FrmSubjecClassRelation.
Items.
Select((value, index) => new { value, index }).
Where(pair => pair.value.UniqueValue == uniqueKey ).
Select(pair => pair.index + 1).
FirstOrDefault() - 1;
// Check the item in listView
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(itemIndexInCheckedListView,
CheckState.Checked);
}
If you do not have such Unique column you may want to add it(just make it hidden)
OR even better - use full-blown DataBinding - http://msdn.microsoft.com/en-us/library/fbk67b6z(v=vs.90).aspx;
I'm using a CheckedListBox (System.Windows.Forms.CheckListBox) and running through some code to populate items in the list using a DataSet. My problem is that I can't seem to figure out how to set the Selected Value property, or find the right property to set!
Here's my code that successfully adds in the items:
for (int i = 0; i < projectsDataSet.tblResources.Rows.Count; i++)
{
clbResources.Items.Add(projectsDataSet.tblResources.Rows[i]["Description"].ToString());
}
There are no useful overloads on the .Add method that takes a value parameter and I can't seem to get to a value property of an item.
I guess the bottom line of what I need is the items in the CheckedListBox to display items using one field from my DataSet (like a description) and use another to store that item's value (like a primary key), so would appreciate suggestions to achieve that, thanks!
First make a class for your list box items...
public class Thing
{
public string Key { get; set; }
public string Value { get; set; }
public override string ToString()
{
return Key + "--" + Value;
}
}
Then add items to your CheckListBox like so:
for (int i = 0; i < projectsDataSet.tblResources.Rows.Count; i++)
{
clbResources.Items.Add(new Thing()
{
Key = projectsDataSet.tblResources.Rows[i]["Key"].ToString(),
Value = projectsDataSet.tblResources.Rows[i]["Description"].ToString()
}, isChecked);
}
I had had the same issue. Luckily you there is workaround to this.
if the number of items and order of items in ListBox & DataTable is same then you can get the corresponding value as below
ListBox.SelectedIndexCollection items = checkedListBox1.SelectedIndices;
for(int i=0;i<items.Count;i++)
string selectedValue = projectsDataSet.tblResources.Rows[items[i]]["ValueColumn"].ToString();
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(',');
I have a string "test1" and my comboBox contains test1, test2, and test3. How do I set the selected item to "test1"? That is, how do I match my string to one of the comboBox items?
I was thinking of the line below, but this doesn't work.
comboBox1.SelectedText = "test1";
This should do the trick:
Combox1.SelectedIndex = Combox1.FindStringExact("test1")
Have you tried the Text property? It works for me.
ComboBox1.Text = "test1";
The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.
Assuming that your combobox isn't databound you would need to find the object's index in the "items" collection on your form and then set the "selectedindex" property to the appropriate index.
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");
Keep in mind that the IndexOf function may throw an argumentexception if the item isn't found.
If the items in your ComboBox are strings, you can try:
comboBox1.SelectedItem = "test1";
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String");
Try this in windows Form.
For me this worked only:
foreach (ComboBoxItem cbi in someComboBox.Items)
{
if (cbi.Content as String == "sometextIntheComboBox")
{
someComboBox.SelectedItem = cbi;
break;
}
}
MOD: and if You have your own objects as items set up in the combobox, then substitute the ComboBoxItem with one of them like:
foreach (Debitor d in debitorCombo.Items)
{
if (d.Name == "Chuck Norris")
{
debitorCombo.SelectedItem = d;
break;
}
}
SelectedText is to get or set the actual text in the string editor for the selected item in the combobox as documented here . This goes uneditable if you set:
comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
Use:
comboBox1.SelectedItem = "test1";
or:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");
I've used an extension method:
public static void SelectItemByValue(this ComboBox cbo, string value)
{
for(int i=0; i < cbo.Items.Count; i++)
{
var prop = cbo.Items[i].GetType().GetProperty(cbo.ValueMember);
if (prop!=null && prop.GetValue(cbo.Items[i], null).ToString() == value)
{
cbo.SelectedIndex = i;
break;
}
}
}
Then just consume the method:
ddl.SelectItemByValue(value);
comboBox1.SelectedItem.Text = "test1";
I've filled my ComboBox with een DataTable filled from a database. Then I've set the DisplayMember and the ValueMember. And I use this code to set the selected item.
foreach (DataRowView Row in ComboBox1.Items)
{
if (Row["ColumnName"].ToString() == "Value") ComboBox1.SelectedItem = Row;
}
Supposing test1, test2, test3 belong to comboBox1 collection following statement will work.
comboBox1.SelectedIndex = 0;
This solution is based on MSDN with some modifications I made.
It finds exact or PART of string and sets it.
private int lastMatch = 0;
private void textBoxSearch_TextChanged(object sender, EventArgs e)
{
// Set our intial index variable to -1.
int x = 0;
string match = textBoxSearch.Text;
// If the search string is empty set to begining of textBox
if (textBoxSearch.Text.Length != 0)
{
bool found = true;
while (found)
{
if (comboBoxSelect.Items.Count == x)
{
comboBoxSelect.SelectedIndex = lastMatch;
found = false;
}
else
{
comboBoxSelect.SelectedIndex = x;
match = comboBoxSelect.SelectedValue.ToString();
if (match.Contains(textBoxSearch.Text))
{
lastMatch = x;
found = false;
}
x++;
}
}
}
else
comboBoxSelect.SelectedIndex = 0;
}
I hope I helped!
You don't have that property in the ComboBox. You have SelectedItem or SelectedIndex. If you have the objects you used to fill the combo box then you can use SelectedItem.
If not you can get the collection of items (property Items) and iterate that until you get the value you want and use that with the other properties.
hope it helps.
_cmbTemplates.SelectedText = "test1"
or maybe
_cmbTemplates.SelectedItem= _cmbTemplates.Items.Equals("test1");
Enumerate ListItems in combobox
Get equal ones listindex set combobox
Set listindex to the found one.
But if I see such a code as a code reviewer, I would recommend to reconsider all the method algorithm.
I used KeyValuePair for ComboBox data bind and I wanted to find item by value so this worked in my case:
comboBox.SelectedItem = comboBox.Items.Cast<KeyValuePair<string,string>>().First(item=> item.Value == "value to match");
Find mySecondObject (of type MyObject) in combobox (containing a list of MyObjects) and select the item:
foreach (MyObject item in comboBox.Items)
{
if (item.NameOrID == mySecondObject.NameOrID)
{
comboBox.SelectedItem = item;
break;
}
}
ListItem li = DropDownList.Items.FindByValue("13001");
DropDownList.SelectedIndex = ddlCostCenter.Items.IndexOf(li);
For your case you can use
DropDownList.Items.FindByText("Text");
combo.Items.FindByValue("1").Selected = true;
All methods, tricks, and lines of code setting ComboBox item will not work until the ComboBox has a parent.
I have created a Function which will return the Index of the Value
public static int SelectByValue(ComboBox comboBox, string value)
{
int i = 0;
for (i = 0; i <= comboBox.Items.Count - 1; i++)
{
DataRowView cb;
cb = (DataRowView)comboBox.Items[i];
if (cb.Row.ItemArray[0].ToString() == value)// Change the 0 index if your want to Select by Text as 1 Index
{
return i;
}
}
return -1;
}
this works for me.....
comboBox.DataSource.To<DataTable>().Select(" valueMember = '" + valueToBeSelected + "'")[0]["DislplayMember"];
I know this isn't what the OP asked but could it be that they don't know? There are already several answers here so even though this is lengthy I thought it could be useful to the community.
Using an enum to fill a combo box allows for easy use of the SelectedItem method to programmatically select items in the combobox as well as loading and reading from the combobox.
public enum Tests
{
Test1,
Test2,
Test3,
None
}
// Fill up combobox with all the items in the Tests enum
foreach (var test in Enum.GetNames(typeof(Tests)))
{
cmbTests.Items.Add(test);
}
// Select combobox item programmatically
cmbTests.SelectedItem = Tests.None.ToString();
If you double click the combo box you can handle the selected index changed event:
private void cmbTests_SelectedIndexChanged(object sender, EventArgs e)
{
if (!Enum.TryParse(cmbTests.Text, out Tests theTest))
{
MessageBox.Show($"Unable to convert {cmbTests.Text} to a valid member of the Tests enum");
return;
}
switch (theTest)
{
case Tests.Test1:
MessageBox.Show("Running Test 1");
break;
case Tests.Test2:
MessageBox.Show("Running Test 2");
break;
case Tests.Test3:
MessageBox.Show("Running Test 3");
break;
case Tests.None:
// Do nothing
break;
default:
MessageBox.Show($"No support for test {theTest}. Please add");
return;
}
}
You can then run tests from a button click handler event:
private void btnRunTest1_Click(object sender, EventArgs e)
{
cmbTests.SelectedItem = Tests.Test1.ToString();
}
if you are binding Datasource via Dataset, then you should use "SelectedValue"
cmbCategoryList.SelectedValue = (int)dsLookUp.Tables[0].Select("WHERE PRODUCTCATEGORYID = 1")[0]["ID"];
You can say comboBox1.Text = comboBox1.Items[0].ToString();
Please try this way, it works for me:
Combobox1.items[Combobox1.selectedIndex] = "replaced text";
It should work
Yourcomboboxname.setselecteditem("yourstring");
And if you want to set database string use this
Comboboxname.setselecteditem(ps.get string("databasestring"));