c# dataGridView cell添加下拉框
应用场景:
dataGridView需要某一个cell变成下拉框样式。
思路详解:
dataGridVie添加固定格式的row。
代码:
DataGridViewRow row = new DataGridViewRow(); row.Cells.Add(new DataGridViewTextBoxCell()); DataGridViewComboBoxCell comboxcell = new DataGridViewComboBoxCell(); comboxcell.Items.Add("九"); comboxcell.Items.Add("平"); comboxcell.Items.Add("气"); comboxcell.Items.Add("阴"); comboxcell.Items.Add("阳"); comboxcell.Items.Add("痰"); comboxcell.Items.Add("气"); comboxcell.Items.Add("血"); comboxcell.Items.Add("特"); comboxcell.Items.Add("湿"); row.Cells.Add(comboxcell); row.Cells.Add(new DataGridViewTextBoxCell()); row.Cells.Add(new DataGridViewTextBoxCell()); row.Cells.Add(new DataGridViewTextBoxCell()); dataGridView_pinggu.Rows.Add(row);
下拉框事件代码:
private void dataGridView_pinggu_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { DataGridView dgv = sender as DataGridView; //判断相应的列 if (dgv.CurrentCell.GetType().Name == "DataGridViewComboBoxCell" && dgv.CurrentCell.RowIndex != -1) { //给这个DataGridViewComboBoxCell加上下拉事件 (e.Control as ComboBox).SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged); } } public void ComboBox_SelectedIndexChanged(object sender, EventArgs e) { ComboBox combox = sender as ComboBox; //这里比较重要 combox.Leave += new EventHandler(combox_Leave); try { //在这里就可以做值是否改变判断 if (combox.SelectedItem != null) { Console.WriteLine(combox.SelectedItem.ToString()); int manNum = ShuJuFenXiService.getNumBySexAndProjectID("0", tizhiDic[combox.SelectedItem.ToString()]); int famNum = ShuJuFenXiService.getNumBySexAndProjectID("1", tizhiDic[combox.SelectedItem.ToString()]); dataGridView_pinggu.Rows[1].Cells[1].Value = combox.SelectedItem.ToString(); dataGridView_pinggu.Rows[1].Cells[2].Value = manNum + famNum; dataGridView_pinggu.Rows[1].Cells[3].Value = manNum; dataGridView_pinggu.Rows[1].Cells[4].Value = famNum; dataGridView_pinggu.Rows[1].Cells[5].Value = tizhiDic[combox.SelectedItem.ToString()]; } Thread.Sleep(100); } catch (Exception ex) { MessageBox.Show(ex.Message); } } public void combox_Leave(object sender, EventArgs e) { ComboBox combox = sender as ComboBox; //做完处理,须撤销动态事件 combox.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged); }
难点:
1.注意dataGridView属性readOnly,设成false(界面模板设置))。要不然下拉框不显示。如果需要不可编辑,可以设定单元格的readOnly属性: dataGridView_pinggu.Rows[1].Cells[1].ReadOnly = true;
2.下拉框事件仅需给datagridview添加EditingControlShowing事件。