Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
how to track selectedIndexChanged event of a Combobox in DataGridView
Posted
Updated 29-Mar-13 20:53pm
v2
Comments
[no name] 30-Mar-13 3:11am    
You cannot track it you will have to create it dynamically.
Sandeep Mewara 30-Mar-13 3:28am    
Elaborate.

ComboBoxCell doesn't support SelectedIndex property, I have found two way to achieve.
1. Set the initial value of the ComboBoxCell.
For example, here is a table with CountryID and CountryName
C#
private DataTable dtCountry = new DataTable();
dtCountry.Columns.Add("CountryID", typeof(int));
dtCountry.Columns.Add("CountryName", typeof(string));
dtCountry.Rows.Add(1, "Canada");
dtCountry.Rows.Add(2, "USA");
dtCountry.Rows.Add(3, "Mexico");


I will create a new DataGridViewComboBoxCell instance and set its initial value with the first row in dtCountry.
C#
DataGridViewComboBoxCell dgvCmbCell = new DataGridViewComboBoxCell();
dgvCmbCell.DataSource = dtCountry;
dgvCmbCell.DisplayMember = "CountryName";
dgvCmbCell.ValueMember = "CountryID";
// use this cell on row[0] cell[1]
dataGridView1.Rows[0].Cells[1] = dgvCmbCell;
if (dataGridView1.Rows[0].Cells[1].Value.ToString() == "")
{
    dgvCmbCell.Value = dtCountry.Rows[0]["CountryID"];
}


2. Set the SelectedIndex to 0 when you click the cell and want to edit it. So you need to handle EditingControlShowing event.
C#
dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    ComboBox cmb = e.Control as ComboBox;
    if (cmb != null)
    {
       cmb.SelectedIndex = 0;
    }
}


Please check out more at this:-http://social.msdn.microsoft.com/Forums/en-US/winformsdesigner/thread/57df7b19-4929-47e3-9793-9a6fba278595/[^][^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900