.NET madness featuring a TabControl, a DataGridView and some HeaderCells

Dienstag, 8.3.2016, 11:46 > daMax

I think I just found a bug in the .NET-Framework (v4.5). I can reproduce this in VS2015 in Visual Basic, I haven't tried it in C# as of yet.

Here's what I wanted to achieve:

Task: Create a Windows Form with a Tabcontrol. The second tab has a DataGridView. This DataGridView should show some values in each row's HeaderCell.

The usual approach:

1. Create a new Form. Add a TabControl. The first TabPage is empty:

Screenshot_160308_11-17-10

the second TabPage features a DataGridView:

Screenshot_160308_11-17-23

Please note that initially the first TabPage is selected!

2. In your Form.New(), create a DataTable and databind it to the DataGridView:

Public Sub New()

' This call is required by the designer.
InitializeComponent()

' Add any initialization after the InitializeComponent() call.
Dim dt As New DataTable("SomeLines")
Dim col As DataColumn
col = New DataColumn("Col 1", Type.GetType("System.String"))
dt.Columns.Add(col)

col = New DataColumn("Col 2", Type.GetType("System.String"))
dt.Columns.Add(col)

For i As Integer = 0 To 10
Dim row As DataRow = dt.NewRow()
row(0) = "BLA" & i
row(1) = "something"
dt.Rows.Add(row)
Next

Me.DataGridView1.DataSource = dt
End Sub

3. In the Load()-Event of the form, write your HeaderCell.Values:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
For i As Integer = 0 To Me.DataGridView1.RowCount - 1
Me.DataGridView1.Rows(i).HeaderCell.Value = _
Me.DataGridView1.Rows(i).Cells(0).Value
Next
End Sub

The bug: The row headers are always empty!

Screenshot_160308_11-22-25

But: if you CTRL-X / CTRL-V the DataGridView to the first TabPage, the code magically works:

Screenshot_160308_11-23-56

The workaround: Before writing the HeaderCell-contents, make sure that the TabPage featuring the DataGridView is selected! You may deselect it afterwards:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.TabControl1.SelectedIndex = 1
For i As Integer = 0 To Me.DataGridView1.RowCount - 1
Me.DataGridView1.Rows(i).HeaderCell.Value = Me.DataGridView1.Rows(i).Cells(0).Value
Next
Me.TabControl1.SelectedIndex = 0
End Sub

Result:

Screenshot_160308_11-26-37

Here's the Visual-Studio-Solution for download in case you want to reproduce the bug: DataGridViewHeaderCells.zip

I've got to write this to StackOverflow tonight. Finding this took me nearly a day! Damn!!