Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

.net - Can a bound DataGridView use text cell for boolean values?

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?

The DGV is read-only.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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";
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...