1

I have a lot of read-only data, and I don't like the clickable look and feel of DataGridViewCheckBoxColumns which are unfortunately the default type for rendering Boolean data.

Is there any way, either before or after using AutoGenerateColumns of a DataGridView that I can force it to generate DataGridViewTextBoxColumns that would just print TRUE or FALSE instead of DataGridViewCheckBoxColumns?

Sample of way Data currently is returned

If it is easier to address this problem on the DataTable before setting it as the DataSource, that would be fine too.

4

2 に答える 2

1

If you want to continue using AutoGenerateColumns = True and DataGridViewCheckBoxColumn, you can modify the appearance and behavior to look and act like a read only field.

Assuming you wanted to target all CheckBoxCells, you can disable them and change their appearance like this:

For Each row In DataGridView1.Rows.Cast(Of DataGridViewRow)()
    For Each cell In row.Cells.OfType(Of DataGridViewCheckBoxCell)()
        cell.ReadOnly = True
        cell.FlatStyle = FlatStyle.Flat
        cell.Style.ForeColor = Color.DarkSlateGray
    Next
Next
于 2014-04-30T15:39:03.163 に答える
0

I thought I'd share my workaround for the above problem in case any one else was trying to accomplish the same thing. I just turn off AutoGenerateColumns and create my own columns by looping through the column collection in the DataTable. It's important to clear the data source and columns each time in case they differ from call to call. Other than that, I just set the col name, header, and data property from the DataTable column and we're good to go.

''' <summary>
''' Generates DataGridViewTextBox Columns for every field of data in the data source
''' </summary>
''' <param name="dgv">The DataGridView having columns and data generated</param>
''' <param name="dt">The source data as a DataTable</param>
''' <remarks></remarks>
Private Sub AutoGenerateTextBoxColumns(ByVal dgv As DataGridView, ByVal dt As DataTable)
    'declare local variables
    Dim column As DataGridViewTextBoxColumn
    'first clear datasource and columns
    If Not IsNothing(dgv.DataSource) Then dgv.DataSource.Clear()
    'clear way for potentially different columns
    If Not IsNothing(dgv.Columns) Then dgv.Columns.Clear()
    'set autogenerate columns to false
    dgv.AutoGenerateColumns = False
    'generate columns for DataGridView
    For Each col As DataColumn In dt.Columns
        column = New DataGridViewTextBoxColumn()
        With column
            .HeaderText = col.ColumnName
            .DataPropertyName = col.ColumnName
            .Name = col.ColumnName
        End With
        dgv.Columns.Add(column)
    Next
    'add datatable as datasource
    dgv.DataSource = dt
End Sub
于 2012-12-05T15:15:12.153 に答える