0

我有一个带有 TextBoxColumn 的 DataGridView。我希望能够单击单元格以进入编辑模式,当我这样做时,将出现一个下拉菜单,其中包含供用户选择的选项,或者如果用户不想要这些选项之一,他们可以进行编辑单元格(好像没有下拉菜单)。然后,当用户离开单元格时,值(他们键入的内容或他们选择的内容)将被保存。

将用户键入的选项添加到下拉列表中有很多答案,但这不是我想要的。我只想在用户离开并做出自己的选择之前考虑一些常见的选项。

我不想有一个按钮来弹出另一个输入对话框。我不想将列转换为 ComboBoxColumn。我不在乎是否始终显示下拉箭头。

我曾尝试在 EditingContolShowing 上将 TextBoxCell 更改为 ComboBoxCell,但事实证明这是徒劳的。

对此有什么建议吗?

4

2 回答 2

1

只需将要成为 ComboBox 的单元格设置为 DataGridViewComboBoxCell 类型:

var cb1 = new DataGridViewComboBoxCell();
cb1.Items.Add("Yes");
cb1.Items.Add("No");
dgv.Rows[1].Cells[1] = cb1;

var cb2 = new DataGridViewComboBoxCell();
cb2.Items.Add("Blue");
cb2.Items.Add("Red");
dgv.Rows[3].Cells[1] = cb2;

然后使用 EditingControlShowing 事件更改 DropDown 的样式以允许编辑:

void dgv_EditingControlShowing(object sender,
                               DataGridViewEditingControlShowingEventArgs e) {
  ComboBox cb = e.Control as ComboBox;
  if (cb != null) {
    cb.DropDownStyle = ComboBoxStyle.DropDown;
  }
}

使用 CellValidating 事件将任何类型的项目添加到列表中,但这些项目尚不存在:

void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
  var cb = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewComboBoxCell;
  if (cb != null && !cb.Items.Contains(e.FormattedValue)) {
    cb.Items.Add(e.FormattedValue);
    if (dgv.IsCurrentCellDirty) {
      dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
    dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue;
  }
}
于 2015-02-06T16:53:43.410 回答
1

您可以使用的一个选项是自动完成。这可以模拟 DataGridViewTextCell 上的大多数所需行为,除了在输入文本单元格时显示所有选项,并且无需将单元格类型转换为 ComboBox。

这可以在 DataGridView EditingControlShowing 事件中处理:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
  if (e.Control is TextBox)
  {
    TextBox box = e.Control as TextBox;
    box.AutoCompleteCustomSource = new AutoCompleteStringCollection();
    box.AutoCompleteCustomSource.AddRange(new string[] { "Foo", "Bar", "Baz" });
    box.AutoCompleteMode = AutoCompleteMode.Suggest;
    box.AutoCompleteSource = AutoCompleteSource.CustomSource;
  }
}

自动完成DGV

给定,用户必须输入文本才能显示任何选项。如果所需的行为需要在输入文本框时显示所有选项,那么这不是您的最佳选择。但是,如果这对所有其他必需的行为(建议的选项、接受非选项条目、不必总是显示等)次要,那么这是一个可行的解决方案。

编辑

这适用于以下所有情况:

  1. DataGridView 是数据绑定的。

绑定数据源:

public BindingList<Example> Examples { get; set; }

this.Examples = new BindingList<Example>();
dataGridView1.DataSource = this.Examples;

其中 Example 是一个简单的类:

public class Example
{
  public string First { get; set; }
  public string Last { get; set; }
  public string Test { get; set; }
}
  1. 手动添加列。

只是一个空列:

DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.Name = "Extra";
col.HeaderText = "Extra";
this.dataGridView1.Columns.Add(col);
  1. 1 和 2 合二为一。
于 2015-02-05T18:09:38.683 回答