开发者

MS DataGridView.show fails to work

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜