12

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;
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Azhar
  • 20,500
  • 38
  • 146
  • 211
  • Have you tried setting the .Text/.Value (can't remember which one ComboBox uses) to the item you want selected? – Marvin Smit Feb 22 '12 at 13:55
  • Use a list of class that contains a id, value(any primary key) ,to fill combo datasource , then use selectedvalue property: cmbVendor.SelectedValue – Amen Ayach Feb 22 '12 at 13:56
  • are the if get the value true and probleme in selectedIndex or the if always false ? – Akrem Feb 22 '12 at 13:57
  • 2
    GetFocusedRowCellValue() is not a method of DataGrid. If you use a grid control from another vendor or use extension methods then you have to document that in your question. – Hans Passant Feb 22 '12 at 14:02

10 Answers10

15

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#?.

Community
  • 1
  • 1
Kamil
  • 13,363
  • 24
  • 88
  • 183
13

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>);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ashish Patel
  • 131
  • 1
  • 2
5

You have it in your if:

cmbVendor.SelectedItem = cmbVendor.Items[i];
Rahul
  • 76,197
  • 13
  • 71
  • 125
Steve
  • 213,761
  • 22
  • 232
  • 286
  • 1
    No more need for the loop, directly set the .SelectedItem to 'Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"))' i guess. – Marvin Smit Feb 22 '12 at 13:58
  • sorry not working ... Actually it does not true the if statement – Azhar Feb 23 '12 at 07:38
3

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Azhar
  • 20,500
  • 38
  • 146
  • 211
2

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;
chaosifier
  • 2,666
  • 25
  • 39
  • Selecting the Item works fine with this method. However, none of the answers actually Highlight the selected item when the list is displayed by executing `cmb.DroppedDown=true;` – gridtrak Apr 17 '20 at 21:57
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
b0rg
  • 1,879
  • 12
  • 17
0

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;
    }
0
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String From DataGrid Cell value")

Try this this will work fine in C# Windows application

Muhammad Sohail
  • 828
  • 9
  • 18
0

I know it's a very old question, but I thought I'd add my 0.02 since I ran into a similar problem recently when trying to initialize a C# WinForms ComboBox bound to a data source with a particular selection at Form_Load. In such a case, I found out using the bound source itself (via the BindingSource class) to set the selected item to be a better solution than using any of the ComboBox's Selected[...] methods. The latter calls would fail invariably to select what I wanted the user to see as the default value.

Here's what worked for me (try this code in Form_Load for instance):

// Let's say my datasource is a sorted dictionary for the sake of example
SortedDictionary<int, string> dataSource = new SortedDictionary<int, string>();            

// < Code where your datasource is built or retrieved >

// Data index that I want selected in my combobox
int iDataSourceItemIndex = 2; // Arbitrary index value that I know exists...

// Use a binding source instance before adding your datasource to the combobox
BindingSource bindingSource = new BindingSource(dataSource, null);

// The item selection occurs here!
bindingSource.Position = iDataSourceItemIndex;

// Create and bind the combobox to its datasource, with implicit selected index
ComboBox comboBox1 = new ComboBox();

comboBox1.Name = "MyCombo1";
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.DataSource = bindingSource;

Controls.Add(comboBox1);
-1

this works for me.....

string displayMember = ComboBox.DataSource.To<DataTable>().Select("valueMemberColumn = '" + value + "'")[0]["displayMember"].ToString();
ComboBox.FindItemExact(displayMember, true).Selected = true;
EvilTak
  • 7,091
  • 27
  • 36
Jaydeep Karena
  • 159
  • 1
  • 5
  • 14