JYelton
JYelton

Reputation: 36546

How can I create a Datagridview column to handle nullable bools?

I am displaying data from SQL in a datagridview by using a SqlDataAdapter. (This is a C# Winforms app but this question could just as easily apply to VB.) Some of the columns are a nullable bool.

Currently the datagridview uses a standard CheckBox column, which uses an empty checkbox both for null and false, and a checked checkbox for true.

I would like to create a column that displays no checkbox at all for null values.

What's the best way to approach this problem? I am wondering if I should create a new control that inherits from the DataGridView and go from there.

Upvotes: 5

Views: 2496

Answers (4)

M-Peror
M-Peror

Reputation: 852

You could also override the DataGridView's CellPainting event to selectively not draw the checkbox if the value is null. I've done so on occasion in an application, like so:

private void MyDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
    if (e.ColumnIndex == MyCheckBoxColumn.Index && e.RowIndex >= 0) {
        var paintparts = e.PaintParts;
        if (e.Value == null) {
            paintparts &= ~DataGridViewPaintParts.ContentForeground;
        }
        e.Paint(e.ClipBounds, paintparts);
        e.Handled = true;
    }
}

This tells the grid view, that if the value of the column is null (in case of a bool? value like I had -- if you are using database columns you might need to compare to DBNull.Value, not sure about that) to not paint ContentForeground (which includes the checkbox). In all other cases, painting occurs as usual.

Upvotes: 2

JYelton
JYelton

Reputation: 36546

Here is a solution that I've employed and is currently working:

((DataGridViewCheckBoxColumn)dgvDisplayData.Columns["field_name"]).ThreeState = true;

This is done after the data binding and assuming that the sql field "field_name" is a nullable boolean. Resharper isn't especially happy with this format, providing a "Possible System.NullReferenceException" warning.

I'd still be interested in alternative/better suggestions.

Edit:

I've changed this as follows to avoid potential null value exceptions:

DataGridViewCheckBoxColumn chkCol =
    (DataGridViewCheckBoxColumn)dgvDisplayData.Columns["field_name"];
if (chkCol != null) chkCol.ThreeState = true;

Upvotes: 4

Thebigcheeze
Thebigcheeze

Reputation: 3498

Make a template column with a checkbox, bind the checkbox's Enabled property to your nullable bool's "HasValue" property, and bind the checkbox's checked property to nullableBool.HasValue ? nullableBool.Value : false

Upvotes: 0

Chad
Chad

Reputation: 1562

Easiest way is probably to handle this in the OnRowDatabound Eventhandler in the code behind. You will also probably want to implement a RowUpdating event handler that will set null otherwize you are liable to end up with false being saved.

Upvotes: 0

Related Questions