c#: DataGridView单元格添加下拉列表(combobox) 末蓝、 2022-10-08 05:49 854阅读 0赞 # 介绍 # 在DataGridView单元格中显示下拉列表 ## 方式一 ## 直接选择添加一列类型为DataGridViewComboBoxColumn的列,然后添加数据源即可。但是这种方式的下拉列表看起来并不是十分的美观。 ## 方式二 ## 另用下拉列表覆盖当前单元格。 1. 另外新建ComboBox,并设置下拉选项。 2. 添加如下三个函数,代码如下 private void dataGridView1_CurrentCellChanged(object sender, EventArgs e) { DataGridViewColumn column = dataGridView1.CurrentCell.OwningColumn; //如果是要显示下拉列表的列的话 if (column.Name.Equals("Column3")) { int columnIndex = dataGridView1.CurrentCell.ColumnIndex; int rowIndex = dataGridView1.CurrentCell.RowIndex; Point p = this.dataGridView1.Location; Rectangle rect = dataGridView1.GetCellDisplayRectangle(columnIndex, rowIndex, false); comboBox1.Left = rect.Left + p.X; comboBox1.Top = rect.Top + p.Y; comboBox1.Width = rect.Width; comboBox1.Height = rect.Height; //将单元格的内容显示为下拉列表的当前项 string consultingRoom = dataGridView1.Rows[rowIndex].Cells[columnIndex].Value.ToString(); int index = comboBox1.Items.IndexOf(consultingRoom); comboBox1.SelectedIndex = index; comboBox1.Visible = true; } else { comboBox1.Visible = false; } } private void comboBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (dataGridView1.CurrentCell != null) dataGridView1.CurrentCell.Value = comboBox1.Items[comboBox1.SelectedIndex]; } ## 参考 ## 1. [https://www.cnblogs.com/mayanlong/archive/2011/03/07/1974775.html][https_www.cnblogs.com_mayanlong_archive_2011_03_07_1974775.html] [https_www.cnblogs.com_mayanlong_archive_2011_03_07_1974775.html]: https://www.cnblogs.com/mayanlong/archive/2011/03/07/1974775.html
还没有评论,来说两句吧...