Add ComboBox Control in DataGridView Column and get its Selected Value using C#

T.saravanan
Posted by T.saravanan under Windows Forms category on | Points: 40 | Views : 49372
Hi All,

Here i am given a Code Snippet for How to set a ComboBox Column in DataGridView and how to get that ComboBox Selected Value.


//For Create a ComboBox Column in DataGridView
DataGridViewComboBoxColumn dgvcmb = new DataGridViewComboBoxColumn();
dgvcmb.DisplayMember = "Name";
dgvcmb.ValueMember = "Id";
dgvcmb.Name="Emp Name";
dgvcmb.DataSource = dtData.Copy(); // Here dtData --> its your storing Data.
dataGridView1.Controls.Add(dgvcmb);

//Set Selected Index Event into that ComboBox
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex >= 0)
{
ComboBox cmbBox= e.Control as ComboBox;
cmbBox.SelectedIndexChanged += new EventHandler(comboBox_SelectedIndexChanged);
}
}

// Get Selected Value from that ComboBox
void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(((ComboBox)sender).SelectedValue != null)
{
string sId =((ComboBox)sender).SelectedValue.ToString();
string sName =((ComboBox)sender).Text.ToString();
}
}


I hope this will helpful.
Cheers :)

Comments or Responses

Login to post response