c# - 我可以有一个 DataGridView 单元格,我可以在其中键入内容或从下拉列表中进行选择吗?

标签 c# winforms datagridview

这是我第一次使用 DataGridView,有点不知所措(这么多选项!)。

我想显示一个属性列表,每行一个。每行都是一个名称/值对。属性的名称是固定的,但用户可以自由输入任何值。

现在,由于每个属性都有一个已使用值的列表,我希望这些值在下拉列表中可供用户使用。不过,我也希望用户能够键入一个新值。理想情况下,该值应在用户键入时自动完成。

我已经尝试使用具有 DataGridViewComboBoxColumn 样式的列,并且由于标准组合框支持键入或编辑的工作方式,所以我认为这可行。但是,似乎允许从列表中进行选择(另外,按一个键会自动从列表中选择第一个匹配的条目)。似乎无法键入新值。

我应该设置 844 个属性中的哪一个? :-)

最佳答案

您必须更改组合框 DropDownStyle 以允许用户在组合框处于编辑模式时输入文本,但标准 DataGridView 在设计时不允许此行为,因此您必须采取一些技巧,处理 CellValidating, EditingControlShowing 和 CellValidated 事件。

这是代码(来自 MSDN 论坛,对我有用)。

         private Object newCellValue;
         private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
         {
             if (dataGridView1.CurrentCell.IsInEditMode)
             {
                 if (dataGridView1.CurrentCell.GetType() ==
                 typeof(DataGridViewComboBoxCell))
                 {
                     DataGridViewComboBoxCell cell =
                     (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

                     if (!cell.Items.Contains(e.FormattedValue))
                     {
                         cell.Items.Add(e.FormattedValue);

                         cell.Value = e.FormattedValue;

                         //keep the new value in the member variable newCellValue
                         newCellValue = e.FormattedValue;
                     }
                 }
             }
         }

         private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
         {
             if (e.Control.GetType() ==
typeof(DataGridViewComboBoxEditingControl))
             {
                 ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
             }
         }

         private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
         {
             if (dataGridView1.CurrentCell.GetType() ==
                 typeof(DataGridViewComboBoxCell))
             {
                 DataGridViewCell cell =
                 dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                 cell.Value = newCellValue;
             }
         }

关于c# - 我可以有一个 DataGridView 单元格,我可以在其中键入内容或从下拉列表中进行选择吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13254929/

相关文章:

c# - 如何允许在 MessageBox 上复制消息

c# - 回调 UI 线程时尽量避免异常

c# - 如何从 DataGridView 中删除行?

C#,BindingNavigator,右端丑陋的线条

c# - 断言 xunit 中存在文件的惯用方法是什么?

c# - DllImport 用于一组导入函数

winforms - 自定义选项卡控件未显示在 Visual Studio 窗体设计 View 中

vb.net - 如何设置DataGridView行标签

c# - 我需要一个网络应用程序中的通知系统

c# - 面板固定位置