6

是否可以在单个 DataGridViewColumn 中同时包含 DataGridViewComboBoxCells 和 DataGridViewTextBoxCells?还是我绝对限制每列只有一种类型?

4

1 回答 1

8

对此有一个奇怪的解决方案。
默认情况下,将列创建为 TextBox。
处理单元格单击或单元格进入事件。
如果 ColumnIndex 匹配,则将列类型转换为 ComboBox 并设置项目。
一旦从相应的列索引触发单元格离开事件,将其转换回文本框。
不要忘记在转换之前从 Combo 读取文本并将其设置为 TextBox。

我知道这不是合适的解决方案,但有效。
我很想知道是否有人有更好的主意。

提问者的编辑:

这是我最终写的代码:

// Using CellClick and CellLeave in this way allows us
// to stick combo boxes in a particular row, even if the
// parent column type is different
private void dataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex >= FIRST_COL && e.ColumnIndex <= LAST_COL && e.RowIndex == ROW_OF_INTEREST)
    {
        object value = dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
        dataGrid.Columns[e.ColumnIndex].CellTemplate = new DataGridViewComboBoxCell();
        var cell = new DataGridViewComboBoxCell {Value = value};
        cell.Items.AddRange(_values);
        dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex] = cell;
    }
}

private void dataGrid_CellLeave(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex >= FIRST_COL && e.ColumnIndex <= LAST_COL && e.RowIndex == ROW_OF_INTEREST)
    {
        object value = dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
        dataGrid.Columns[e.ColumnIndex].CellTemplate = new DataGridViewTextBoxCell();
        var cell = new DataGridViewTextBoxCell {Value = value};
        dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex] = cell;
    }
}

此外,在创建列时,我必须确保它是通用列;即不是 DataGridViewTextBoxColumn:

var col = new DataGridViewColumn
              {
                  CellTemplate = new DataGridViewTextBoxCell()
              };

这样,我可以稍后更改 CellTemplate。

于 2011-10-03T19:03:52.870 回答