DataGridView doesn't display Cell Controls when used in UserConrol

Viewed 29

My goal is to create interactive DataGridView, which allows user to set desired parameters using controls such as CheckBoxes, ComboBoxes or NumericUpDowns. Therefore I created new Windows.Form with a DataGridView and populated it with aformentioned controls.

Public Class Form1
    Inherits Form
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        InteractiveDataGridViewTemplate.AppendDatagridView(DataGridView1)
    End Sub
End Class


Public Class InteractiveDataGridViewTemplate    
    Public Shared Sub AppendDatagridView(dgw As DataGridView)
        Dim dt As New DataTable
        dt.Columns.Add("Name")
        For i As Integer = 0 To 10
            dt.Rows.Add("")
        Next
        dgw.DataSource = dt
        dgw.Columns(0).Width = 200
        For Each row In dgw.Rows
            CreateCheckBoxCell(row)
        Next
    End Sub

    Private Shared Sub CreateCheckBoxCell(row As DataGridViewRow)
        Dim chBoxCell As New DataGridViewCheckBoxCell
        row.Cells(0) = chBoxCell
        row.Cells(0).Value = False
    End Sub
End Class

Everything worked as expected. The problem occured when instead of Windows.Form I applied the very same procedure on UserControl. In this case all DataGridViewCells turned into TextBoxCells displaying the value intended as starting value for controls (as visualized bellow).

Public Class DgwUserControl
    Inherits UserControl
    Private Sub UserControl_Load(s As Object, e As EventArgs) Handles MyBase.Load    
        InteractiveDataGridViewTemplate.AppendDatagridView(DataGridView1)
    End Sub
End Class

Comparison of the outputs

Is there any explanation for this strange behaviour? And are there are any ways of resolving this issue? Thank you very much for your input.

1 Answers

The designer is probably interfering with it. Try mocking a Shown event in the UserControl to overcome that:

Public Class UserControl1

  Private wasShown As Boolean = False

  Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'InteractiveDataGridViewTemplate.AppendDatagridView(DataGridView1)
  End Sub

  Protected Overrides Sub OnPaint(e As PaintEventArgs)
    If Not wasShown Then
      wasShown = True
      InteractiveDataGridViewTemplate.AppendDatagridView(DataGridView1)
    End If

    MyBase.OnPaint(e)
  End Sub
End Class
Related