How can I set selected in a ComboBox, based on ValueMember? - c#

I have a combobox with the following structure. Also, I am getting a fld_id from another source and based on that id I need to select the corresponding item in the ComboBox. How can I do that?
comboBoxCustomers.DataSource = customers;
comboBoxCustomers.ValueMember = "fld_id";
comboBoxCustomers.DisplayMember = "fld_name";
Example:
List could contain these items
fld_id fld_name
65 Item1
68 Item2
69 Item3
I need to set Item 68 as selected.

Use Following:
comboBoxCustomers.SelectedValue = fld_id(which you are getitng from another source)

I don't have enough reputation to post a comment. This:
comboBoxCustomers.SelectedValue = fld_id
works great :) But AFTER showing the form, otherwise it will fail.

if you use datasource of the combobox, you can cast the datasource back to the list, find the item and use that item to set the selected item:
var stores = cbxStores.DataSource as List<store>;
var store = stores.Where(w => w.store_code == _station.store_code).FirstOrDefault();
cbxStores.SelectedItem = store;

Simplest procdure I found for myself:
You can bind it into some function with perameters while funtion is called.
Hope it is going to help you guys:
int Idd = Convert.ToInt32(your value for the combobox you want to be selected);
for (int i = 0; i < myComboBox.Items.Count; i++)
{
myComboBox.SelectedIndex = i;
if (Convert.ToInt32( myComboBox.SelectedValue ) == Idd )
{break;}
}

Related

how to get the selected values of Listbox in c#

i had bind the listbox where datasource of listbox is list.how can i get the selected value of selected list item in listbox.my sample code as follows
pdfList = attendanceDetailsPresenter.GetPredefinedDetails();
this.lstCompanies.DataSource = pdfList;
this.lstCompanies.DisplayMember = "CompanyName";
this.lstCompanies.ValueMember = "CompID";
this.lstDepartments.BindingContext = new BindingContext();
this.lstDepartments.DataSource = pdfList;
this.lstDepartments.DisplayMember = "DepartmentName";
this.lstDepartments.ValueMember = "DeptID";
if (lstCompanies.SelectedItems.Count < 0)
{
MessageBox.Show("Please Select Any one Company");
return attendanceCalculationDetailsDataList;
}
else
{
for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
attendanceCalculationDetailsData.CompanyID.Add(int.Parse(lstCompanies.SelectedValue.ToString()));
}
}
can anyone solve my problem please.
First of all, the Count of a list can never be less than zero. It's always >= 0.
Then, when you data-bind your list, the items usually are of type DataRowView (which you should be able to verify by debugging your application). If that is right, you should have to cast each selected item to DataRowView and then cast the value of its Row property to the type you expect.
I just noticed that in the following loop you're not even using the selected items, but always the SelectedValue:
for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
attendanceCalculationDetailsData.CompanyID.Add(int.Parse(lstCompanies.SelectedValue.ToString()));
}
Try changing this to:
for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
attendanceCalculationDetailsData.CompanyID.Add(((<WhatEverClassYouUse>)lstCompanies.SelectedItems[i]).CompanyID);
}
Explanation: If more than one item in the list are selected, the items are added to the SelectedItems collection. You can iterate these items. Each item will be an object of DataRowView (when data bound to a DataTable or DataView) or a class in a collection.
As you didn't tell us the type of objects returned by GetPredefinedDetails, I substituted it with WhatEverClassYouUse. Cast this to the right type.

Select next item in ListView

I have a method that removes currently selected item in a ListView
listView1.Items.Remove(listView1.SelectedItems[0]);
How do I select the next in the ListView after removing the selected one?
I tried something like
var index = listView1.SelectedItems[0].Index;
listView1.Items.Remove(listView1.SelectedItems[0]);
listView1.SelectedItems[0].Index = index;
But I get the error
Property or indexer 'System.Windows.Forms.ListViewItem.Index' cannot be
assigned to -- it is read only
Thank you.
I had to add one more line of code to a previous answer above, plus a check to verify the count was not exceeded:
int selectedIndex = listview.SelectedIndices[0];
selectedIndex++;
// Prevents exception on the last element:
if (selectedIndex < listview.Items.Count)
{
listview.Items[selectedIndex].Selected = true;
listview.Items[selectedIndex].Focused = true;
}
ListView doesn't have a SelectedIndex property. It has a SelectedIndices property.
Gets the indexes of the selected items in the control.
ListView.SelectedIndexCollection indexes = this.ListView1.SelectedIndices;
foreach ( int i in indexes )
{
//
}
try use listView1.SelectedIndices property
If you delete an item, the index of the "next" item is the same index as the one you just deleted. So, I would make sure you have listview1.IsSynchroniseDwithCurrentItemTrue = true and then
var index = listView1.SelectedItems[0].Index;
listView1.Items.Remove(listView1.SelectedItems[0]);
CollectionViewSource.GetDefaultView(listview).MoveCurrentTo(index);
I've done this in the following manner:
int selectedIndex = listview.SelectedIndices[0];
selectedIndex++;
listview.Items[selectedIndex].Selected = true;
I actually had to do this:
int[] indicies = new int[listViewCat.SelectedIndices.Count];
listViewCat.SelectedIndices.CopyTo(indicies, 0);
foreach(ListViewItem item in listViewCat.SelectedItems){
listViewCat.Items.Remove(item);
G.Categories.Remove(item.Text);
}
int k = 0;
foreach(int i in indicies)
listViewCat.Items[i+(k--)].Selected = true;
listViewCat.Select();
to get it to work, none of the other solutions was working for me.
Hopefully, a more experienced programmer can give a better solution.

How to set Selected item of ComboBox in C# Windows Forms?

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;

Getting Label Text of CheckBox from a CheckedListBox

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

Assign valuefield and textfield to listbox

i develop a webpage in that i need to add value field and text field to listbox item
i tried the following code , but it's not working , Please help me to solve the issue .
Thanks in advance
string[] category = new string[100];
char[] delimeter = { '~' };
category = Convert.ToString(dtable.Rows[0].ItemArray[5]).Split(delimeter);
for (int h = 0; h < category.Length; h++)
{
ListItem lstitem = lstCategory.Items.FindByText(category[h]);
if (lstitem != null)
{
lstSelCategory.DataTextField = category[h];
lstSelCategory.DataValueField = lstitem.Value;
}
}
lstSelCategory.DataBind();
}
DataValueField and DataTextField are for assigning which properties are displayed and used as values for the assigned DataSource, NOT for adding items to the List.
EDIT:
It looks to me as though you're looping through some categories from a DataTable, finding a matching item in another ListBox and then trying to add that item to another ListBox... You should be using the Add method of the ListBox (if that's what the Control is).
lstSelCategory.Items.Add(new ListItem(category[h], lisitem.Value));
ListBox.DataTextField and ListBox.DataValueField are used in conjuction with ListBox.DataSource.
See this for further information.

Categories