I have a CheckedListBox named Itemlist. And its DataSource is a data table. I have set a DisplayMember as "Name" , and a ValueMember as "NameInt". Is there a reliable way that I can loop through this CheckedListBox and get the ValueMember of the checked items?
Assuming a public property holding your DataTable:
public DataTable Table { get; set; }
Noting the CheckedListBox is named Itemlist (in case edit's occur) - and assuming NameInt is of type int, we can loop through the checked items, grab the index, then get the associated ValueMember directly from the source:
List<int> checkedValueMembers = new List();
foreach (int index in Itemlist.CheckedIndices)
{
checkedValueMembers.Add(Table.Rows[index].Field<int>("NameInt"));
}
Note: I was adding the values to a list as an example, but that should give you the general idea..
for (int i = 0; i < dataSet.tblResources.Rows.Count; i++)
{
clbResources.Items.Add(new Thing()
{
Key = dataSet.tblResources.Rows[i]["Key"].ToString(),
Value = dataSet.tblResources.Rows[i]["Description"].ToString()
}, isChecked);
}
This is from one of my projects. Change accordingly.
Related
I'm using a ComboBox with items having text and value. Now, I want to simply make an item selected by comparing its value with the provided value. I'm iterating through the items and comparing as follow. Below code works fine, but is there a better or more simpler way to do this? I found a possible duplicate here but it works with the string value not integer.
foreach (ComboboxItem item in this.CampaignList.Items)
{
if (Convert.ToInt16(item.Value) == objAACampaign.CompanyId)
{
this.CampaignList.SelectedIndex = this.CampaignList.Items.IndexOf(item);
break;
}
}
Use display and value memeber
Create custom class like this:
class MyCustomClass
{
//important to have get set part
public _int { get; set; }
public _string { get; set; }
}
now load data you want to display inside List<MyCustomClass>() and then bind that list to combobox and set it's display and value member like this:
myComboBox.DisplayMember = "_string";
myComboBox.ValueMember = "_int";
myComboBox.DataSource = myList; //this is List<MyCustomClass>
Now simply use myComboBox.SelectedValue = valueYouWant
IMPORTANT!!!
Declare displayMember and valueMember before binding datasource to combobox because of perfomance. Search internet for more info.
I have a DataTable with 2 columns called "ID" and "Software" that I have used as a DataSource for a lst_Software multiselect listbox.
I'm trying to gather the ID for all the selected items in that have been selected and place that in an int[] array.
Listbox setup:
lst_Software.DataSource = software; //software is a DataTable
lst_Software.DisplayMember = "Software";
lst_Software.ValueMember = "ID";
I've tried below
List<int> list = new List<int>();
for (int i = 0; i < lst_Software.SelectedItems.Count; i++)
{
list.Add(Convert.ToInt32(lst_Software.SelectedValue.ToString()));
}
int[] software = list.ToArray();
I'm finding that I'm only getting the first selected value except it will not iterate through all... I know why though. I'm not using i to get passed through inside the for loop. I'm hoping someone can give me a direction to go to iterate through all the selected values.
Thank you
You're using lst_Software.SelectedValue.ToString() here in the loop so it only returns the one item. You have a for loop but you're not using the index variable. However, all of this is unnecessary really all you need is;
var items = lst_Software.SelectItems;
As that property is already the list of selected items. From there you can cast/convert them as you please.
SelectedValue is just the first selected value. You need to use SelectedItems.
I have table with 4 primary key fields. I load that in to drop down list in my WinForm application created by using C#.
On the TextChanged event of drop down list I have certain TextBox and I want to fill the information recived by the table for the certain field I selected by the drop down list.
So as I say the table having 4 fields. Can I get those all 4 fields into value member from the data set, or could you please tell me whether is that not possible?
Thank you.
Datatable dt=dba.getName();
cmb_name.ValueMember="id";
cmb_name.DisplayMember="name";
cmb_name.DataSource=dt;
this is normal format.. but i have more key fields.. so i need to add more key fields..
You can use DataSource property to bind your source data to the ComboBox (e.g. a List of Entities, or a DataTable, etc), and then set the DisplayMember property of the ComboBox to the (string) name of the field you want to display.
After the user has selected an Item, you can then cast the SelectedItem back to the original row data type (Entity, DataRow, etc - it will still be the same type as you put in), and then you can retrieve your 4 composite keys to the original item.
This way you avoid the SelectedValue problem entirely.
Edit:
Populate as follows:
cmb_name.DisplayMember = "name";
cmb_name.DataSource = dt;
// Ignore ValueMember and Selected Value entirely
When you want to retrieve the selected item
var selectedRow = (cmb_name.SelectedItem as DataRowView );
Now you can retrieve the 4 values of your PK, e.g. selectedRow["field1"], selectedRow["field2"], selectedRow["field3"] etc
If however you mean that you want to DISPLAY 4 columns to the user (i.e. nothing to do with your Table Key), then see here How do I bind a ComboBox so the displaymember is concat of 2 fields of source datatable?
cmb_name.DisplayMember = "name";
cmb_name.DataSource = dt;
DataRowView selectedRow = (cmb_name.SelectedItem as DataRowView );
The result will be here:
MessageBox.Show(selectedRow.Row[0].ToString());
MessageBox.Show(selectedRow.Row[1].ToString());
MessageBox.Show(selectedRow.Row[2].ToString());
MessageBox.Show(selectedRow.Row[3].ToString());
.....
If you want to get some data from a ComboBox in to a List you can use something like this
List<string> ListOfComboData = new List<string>();
ListOfComboData = yourComboBox.Items.OfType<string>().ToList<string>();
I have no real idea if this is what you mean as the question is very poorly structured. I hope this helps...
Edit: To put the selected text in to some TextBox use
yourTextBox.Text = youComboBox.Text;
in the SelectedIndexChanged event of your ComboBox.
You could follow the approach here with the following class:
public class ComboBoxItem
{
public string Text { get; set; }
public object[] PrimaryKey { get; set; }
}
private void Test()
{
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.PrimaryKey = new object[] { primaryKey1, primaryKey2, primaryKey3, primaryKey4};
comboBox1.Items.Add(item);
comboBox1.SelectedIndex = 0;
MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());
}
I am trying to set selected item of comboBox on click event of DataGrid, but I could not. I have googled and tried different ways but without success.
For me SelectedIndex is working, but I could not find the index of items in ComboBox, so I could not select the item.
Not working code:
for (int i = 0; i < cmbVendor.Items.Count; i++)
if (cmbVendor.Items[i].ToString() == Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor")))
{
cmbVendor.SelectedIndex = i;
break;
}
You can get your item index by the .Items.IndexOf() method. Try this:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf(gridView1.GetFocusedRowCellValue("vVendor"));
You don't need to iterate.
You can find more information in Stack Overflow question How do I set the selected item in a comboBox to match my string using C#?.
The following is working for me perfectly. Pass any value or Text which is available in the combobox.
comboBox1.SelectedIndex = comboBox1.FindString(<combobox value OR Text in string formate>);
You have it in your if:
cmbVendor.SelectedItem = cmbVendor.Items[i];
At last I found it out. It's:
cmbVendor.Text = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.
If you have set ValueMember property for the ComboBox control, you can simply assingn the Value to the ComboBox control's SelectedValue property. You don't have to find the index explicitly.
Here's an example:
public class Vendor{
public int VendorId {get; set;}
public string VendorName {get; set;}
}
// Inside your function
var comboboxData = new List<Vendor>(){
new Vendor(){ vendorId = 1, vendorName = "Vendor1" },
new Vendor(){ vendorId = 2, vendorName = "Vendor2" }
}
cmbVendor.DataSource = comboboxData;
cmbVendor.DisplayMember = "VendorName";
cmbVendor.ValueMember = "ValueId";
// Now, to change your selected index to the ComboBox item with ValueId of 2, you can simply do:
cmbVendor.SelectedValue = 2;
Assuming gridView1.GetFocusedRowCellValue("vVendor") really works as expected, the following code should fix the problem.
string selected = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
foreach ( var item in cmbVendor.Items )
{
if (string.Compare(item.ToString(), selected, StringComparison.OrdinalIgnoreCase) == 0)
{
cmbVendor.SelectedItem = item;
break;
}
}
The original code had multiple calls to gridView1.GetFocusedRowCellValue("vVendor"), whereas you only need one.
The suggested "comboBox1.Items.IndexOf(" assumes too much about the content of cmbVendor.Items.
I had a similar problem and worked it out partially with the help of the other answers here. First, my particular problem was that
combobox1.SelectedItem = myItem;
was not working as expected. The root cause was that myItem was an object from a group which was effectively the same list as the items in the combobox, but it was actually a copy of those items. So myItem was identical to a valid entry, but itself was not a valid object from the combobox1 container.
The solution was to use SelectedIndex instead of SelectedItem, like this:
combobox1.SelectedIndex = get_combobox_index(myItem);
where
private int get_combobox_index(ItemClass myItem)
{
int i = 0;
var lst = combobox1.Items.Cast<ItemClass >();
foreach (var s in lst)
{
if (s.Id == myItem.Id)
return i;
i++;
}
return 0;
}
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String From DataGrid Cell value")
Try this this will work fine in C# Windows application
this works for me.....
string displayMember = ComboBox.DataSource.To<DataTable>().Select("valueMemberColumn = '" + value + "'")[0]["displayMember"].ToString();
ComboBox.FindItemExact(displayMember, true).Selected = true;
I currently have a CheckedListBox with several boxes. I want to be able to test every Checkbox in the list to see if it's checked, and if it is, add it's text value (CheckBox.Text) to a List of strings.
Here is what I have:
for ( int i = 0; i < multiTaskChecks.Items.Count; i++ )
{
if ( multiTaskChecks.GetItemChecked(i) )
{
checkedMultiTasks.Add(multiTaskChecks.GetItemText(i));
}
}
Using this, GetItemText is returning 0, 1, 2, 3, etc instead of the text values that I'm after. I have also tried CheckedListBox.Text.IndexOf(i), CheckedListBox.Text.ToList(), each without any luck.
I just cannot get the label text of one of these CheckBoxes from the CheckedListBox. Any help with this would be really appreciated.
Firstly, you should be able to loop through the checked items only like so
foreach (var item in multiTaskChecks.CheckedItems)
{
}
then depending on the type of the item, get whatever property you want from it. Sounds like it is just a Text or you just want the string, so
foreach (var item in multiTaskChecks.CheckedItems)
{
checkedMultiTasks.Add(item.ToString());
}
or I prefer
checkedMultiTasks.AddRange(multiTaskChecks.CheckedItems.
OfType<object>().Select(i => i.ToString()));
Try this:
for (int i = 0; i < multiTaskChecks.Items.Count; i++)
{
if (multiTaskChecks.GetItemChecked(i))
{
checkedMultiTasks.Add(multiTaskChecks.GetItemText(multiTaskChecks.Items[i]));
}
}
ListControl.GetItemText Method
NOTE There's a caution regarding DisplayMember for this method:
If the DisplayMember property is not specified, the value returned by GetItemText is the value of the item's ToString method. Otherwise, the method returns the string value of the member specified in the DisplayMember property for the object specified in the item parameter.
This should work:
var checkedMultiTasks = new List<string>();
foreach(var item in multiTaskChecks.CheckedItems) {
checkedMultiTasks.Add(item.ToString());
}