views:

9

answers:

1

Hello, I used to have a single DataGridView (DGV) on a form. I formatted and populated this, then used DGV.Show to make it appear on my form. This worked fine.

I upgraded my form, to included 2 DGVs. Within a sub I dim a new DGV, populate and format it as before then set this equal to whichever DGV on the form it's meant to be. For example:

    Dim pDGV as new DataGridView
  with pDGV
    .ColumnHeadersVisible = True
    .RowHeadersVisible = False
    .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
    .ScrollBars = ScrollBars.Both
    .DataSource = pTable 
    .AllowUserToAddRows = False
    .AllowUserToDeleteRows = False
    .ReadOnly = True
  end with

frm1.DGV1 = pDGV

frm1.DGV1.show

During debug, I can see that Frm1.DGV appears to be indentical to pDGV, in that it has the same number of columns and rows etc. However, it fails to show.

I can revert back to populating and formatting each DGV individually, but that duplicates a lot of code. I thought this would be more elegant.

Any ideas as to why the .show won't work?

thanks

A: 

You are trying to assign an instance of DataGridView create at run-time to a DataGridView already created on the form. This is not possible.

You can implement something similar to this to achieve your goal.

Public Class Form1

    Dim _DT As New DataTable

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        _DT.Columns.Add("0")
        For i As Integer = 0 To 9
            _DT.Rows.Add(i)
        Next

        FormatDataGridView(DataGridView1)
        FormatDataGridView(DataGridView2)

    End Sub

    Public Sub FormatDataGridView(ByVal dgv As DataGridView)

        With dgv
            .ColumnHeadersVisible = True
            .RowHeadersVisible = False
            .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
            .ScrollBars = ScrollBars.Both
            .DataSource = _DT
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .ReadOnly = True
        End With

    End Sub

End Class

Otherwise you can create the DataGridView at run-time and then adding to a Panel for example.

marco.ragogna