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

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;

Related

Retrieve a ListViewItem's value

I have a ListView populated with the code below. Ask you can see, I set both the DisplayMember and the ValueMember. What I am wanting to do is find a ListViewItem by its ValueMember. So essentially what I'm looking for is ListViewItem.Value. I know I can get SelectedValue for the ListView itself, but I just don't see any properties on the ListViewItem that give me what I'm looking for. Am I just missing something, or is there no way to do this?
private void PopulateList(Globals.DataFieldMappingTypes mappingType)
{
ListBox lst = GetListBox(mappingType);
ComboBox cbo = cboh.GetComboBox(new ComboBoxHandler.CboInfo(Globals.NodeTypes.DataField, mappingType));
string sql = "select DataFieldReferenceValueId, [Value] from DataFieldReferenceValueInfo where DataFieldId = " + cbo.SelectedValue.ToString();
DataTable tbl = dal.GetTable(sql, "DataFieldReferenceValue");
lst.DisplayMember = "Value";
lst.ValueMember = "DataFieldReferenceValueId";
lst.DataSource = tbl.DefaultView;
}
I think that you are not getting the values from DataTable correctly I guess.
I hope tbl.Rows[0][0].ToString() will have the DataFieldReferenceValueId and
tbl.Rows[0][1].ToString() will have the [Value]
Please check the below MSDN link
https://forums.asp.net/t/1188002.aspx?how+to+read+DataTable+Rows+value+and+put+it+into+the+string+
Instead of loading your dataTable straight in as the dataSource why don't you create a class to define the values?
public class SqlTable
{
public string Name {get;set;}
public string Value {get;set;}
}
var listPair = new List<SqlTable>();
Then load the list with your SqlDataReader and grab your desired pair with LINQ.
while (sdr.Read())
{
listPair.Add(new SqlTable() { Name = sdr[0].ToString(), Value = sdr[1].ToString() });
}
lst.DisplayMember = "Name";
lst.ValueMember = "Value";
lst.DataSoure = listPair;
SqlTable sqlTable = listPair.Find(x => x.Name == "Whatever name you are searching for") as SqlTable;
The SqlTable item is now the one you are searching for and you can get its properties by going:
string value = sqlTable.Value;
string name = sqlTable.Name;
Edit from comment begins here:
Well your first issue is that the 'lst' item in your example is a ListBox and not a ListView. It you switch it to a listview you can still feed your List of listPair items like so:
ListView lst = new ListView();
lst.View = View.Details;
foreach (var data in listPair)
{
lst.Items.Add(new ListViewItem(listPair.Name, listPair.Value);
}
So now you have a ListView that is a collection of your listPairs where each listPair is a ListViewItem. I assume you want to isolate the ListViewItem based on your value (or listPair.Value or sdr[1] or [Value] they are all the same now) in order to color it. You can now grab the listPair item like so:
SqlTable pair = listPair.Find(x => x.Value == "Whatever the Value value is that you want to color");
ListViewItem searchedItem = lst.FindItemWithText(pair.Name);
searchedItem.BackColor = System.Drawing.Color.Red; //or whatever color you choose
You can now use searchedItem to grab its index in the ListView and all its other properties. The ListPair just allows you to associate the values.

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.

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.

C#: How do you make sure that a row or item is selected in ListView before performing an action?

What is the best way to check if there is atleast a selected item in a listview or not in an if statement?
I'm not entirely sure what you are asking. Do you want to make sure at least 1 item is selected before running an action? If so the following should work
if ( listView.SelectedItems.Count > 0 ) {
// Do something
}
Or are you curious if a particular item is selected? If so try the following
if ( listView.SelectedItems.Contains(someItem)) {
// Do something
}
if( listView.SelectedItems.Count > 0 ){
// do stuff here
}
You can also check the value of a selected item or perhaps bind it to a string if needed:
//Below is with string
String member = (String)ListView1.SelectedValue;
//Below is with any class
AnyClass member = (AnyClass)ListView1.SelectedValue;
String StaffID = member.StaffID;
int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);
string taskDate = itemRow.SubItems1.ToString();
string taskDescription = itemRow.SubItems[2].ToString();enter image description here
//Here a simple loop that go through all the items in the list
for (int i = 0; i < listView1.Items.Count; i++)
{
//checks if the item in the list has the value true to the properties checked
if (listView1.Items[x].Checked == true)
{//your code
//e.g.
listView1.Items[x].Checked = false;
}
}
You can also check count of the selected item list by using getCheckedItemCount() method of the listview. for example,
if( listview.getCheckedItemCount() > 0 ) {
// do stuff here
}

Categories