在 DataGridViewColumn 中混合单元格类型 [英] Mixing cell types in a DataGridViewColumn

查看:20
本文介绍了在 DataGridViewColumn 中混合单元格类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to have both DataGridViewComboBoxCells and DataGridViewTextBoxCells in a single DataGridViewColumn? Or am I absolutely restricted to having one type per column?

推荐答案

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

There is a weird solution for this.
By default create the column as TextBox.
Handle the cell click or cell enter event.
In the event if the ColumnIndex matches, Convert the column type to ComboBox and set the items.
Once the cell leave event fires from the respective column index, convert it back to textbox.
Dont forget to read the text from Combo before converting and set it to TextBox.

我知道这不是恰当的解决方案,但有效.
我很想知道是否有人有更好的主意.

I know this is not apt solution but works.
I am eager to know if anyone has a better idea.

提问者的

这是我最终编写的代码:

Here was the code I ultimately wrote:

// 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:

Also, when creating the column, I had to make sure it was a generic column; i.e. not a DataGridViewTextBoxColumn:

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

那样,我可以稍后更改 CellTemplate.

That way, I could change the CellTemplate later.

这篇关于在 DataGridViewColumn 中混合单元格类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆