RSS

Generate DataGridViewColumns manually

05 Mar
Dim dt As DataTable
' ...code to load dt
'
' dt has 3 columns:
' "select", "name", "number"

Dim gv As New DataGridView

gv.Columns.Clear()
gv.AutoGenerateColumns = False
gv.DataSource = dt

Dim checkBoxColumn As DataGridViewCheckBoxColumn = New DataGridViewCheckBoxColumn()
checkBoxColumn.TrueValue = "Y"
checkBoxColumn.FalseValue = "N"
checkBoxColumn.DataPropertyName = "select"    ' The dt column name 
checkBoxColumn.Name = "select"                ' The gv column name
gv.Columns.Add(checkBoxColumn)
' Set column properties
gv.Columns("select").Width = 50
gv.Columns("select").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
gv.Columns("select").HeaderText = "Select"
gv.Columns("select").SortMode = DataGridViewColumnSortMode.NotSortable

Dim textColumn As DataGridViewColumn = New DataGridViewTextBoxColumn()
textColumn.DataPropertyName = "name"
textColumn.Name = "name"
gv.Columns.Add(textColumn)
' Make this column invisible
gv.Columns("name").Visible = False

textColumn = New DataGridViewTextBoxColumn()
textColumn.DataPropertyName = "number"
textColumn.Name = "number"
gv.Columns.Add(textColumn)

' Additional gv manipulation
For Each row As DataGridViewRow In Me.dgvMI4051.Rows
    If row.Cells("name").Value = "Rose" Then
        ' Tick checkbox
        row.Cells("select").Value = "Y"
    ElseIf row.Cells("name").Value = "Jack" Then
        row.Cells("select").Value = "N"
    Else
        ' Make checkboxes invisible
        Dim emptyCell As New DataGridViewTextBoxCell()
        row.Cells("select") = emptyCell
    End If
Next
Advertisements
 
Leave a comment

Posted by on March 5, 2012 in .NET, VB

 

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: