绑定的 DataGridView 可以使用文本单元格作为布尔值吗? [英] Can a bound DataGridView use text cell for boolean values?

查看:13
本文介绍了绑定的 DataGridView 可以使用文本单元格作为布尔值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到对象列表的 DGV.这很好用,只是对象属性之一是布尔值,因此显示为复选框,但我更喜欢简单的是/否文本字段.我已经考虑添加一个额外的列并根据布尔值填充适当的字符串,但这似乎有点过头了.有没有更简单的方法?

I have a DGV bound to a list of objects. This works fine except that one of the object properties is boolean and therefore displays as a checkbox but I would prefer a simple yes/no text field instead. I've considered adding an additional column and populating with the appropriate string based on the boolean value but this seems a little over the top. Is there an easier way?

DGV 是只读的.

推荐答案

如上所述,在数据绑定场景中改变布尔值的视觉外观似乎是不可能的.甚至 DataGridViewCellStyle.FormatProvider 也不能正确处理 System.Int32、System.Int64、System.Decima 等类型.

As mentioned above it seems to be impossible to change the visual appearance of boolean values in a data bound scenario. Even DataGridViewCellStyle.FormatProvider does not work correctly with types like System.Int32, System.Int64, System.Decima, etc.

因此,我找到了一个对我有用的解决方法.可能它不是最好的解决方案,但目前它符合我的需求.我处理了 DataGridView.ColumnAdded 事件并将 DataGridViewCheckBoxColumn 替换为 DataGridViewTextBoxColumn.之后我使用 CellFormating 事件(微软推荐,见上面的链接)来格式化源数据.

Therefore I found a workaround which works for me. Probably it is not the best solution but currently it fits my needs. I handle the DataGridView.ColumnAdded event and replace DataGridViewCheckBoxColumn with DataGridViewTextBoxColumn. Afterwards I use CellFormating event (recommended by Microsoft, see links above) to format source data.

private DataGridViewTextBoxColumn textBoxColumn = null;
void _dataGrid_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
    // Avoid recursion
    if (e.Column == textBoxColumn) return;

    DataGridView gridView = sender as DataGridView;
    if (gridView == null) return;

    if( e.Column is DataGridViewCheckBoxColumn)
    {
        textBoxColumn = new DataGridViewTextBoxColumn();
        textBoxColumn.Name = e.Column.Name;
        textBoxColumn.HeaderText = e.Column.HeaderText;
        textBoxColumn.DataPropertyName = e.Column.DataPropertyName;

        gridView.Columns.Insert(e.Column.Index, textBoxColumn);
        gridView.Columns.Remove(e.Column);
    }
}

void _dataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    DataGridViewColumn col = _dataGrid.Columns[e.ColumnIndex];

    try
    {
        if ( col.Name == "IsMale")
        {
            bool isMale = Convert.ToBoolean(e.Value);
            e.Value = isMale ? "male" : "female";
        }
    }
    catch (Exception ex)
    {
        e.Value = "Unknown";
    }
}

这篇关于绑定的 DataGridView 可以使用文本单元格作为布尔值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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