在将控件添加到表单

时间:2015-06-11 02:46:17

标签: vb.net winforms datagridview

GD All,

我有一个相当简单的表单循环,为选择的记录添加标签页。在添加的选项卡上,它插入DataGridView以显示每个选项卡标识符的记录选择。

为了做到这一点,我创建了以下代码:

    For Each r As DataRow In tnkTable.Rows

        Dim tmpTableAdapter As New RD_BWMDataSetTableAdapters.tblEventRegisterTableAdapter
        Dim newTab As New TabPage()
        Dim newGrid As New DataGridView() With {.Location = New Point(6, 6), .Width = 800}
        Dim newBindingSource As New BindingSource()
        Dim newDataview As DataView

        newDataview = tmpTableAdapter.GetData.AsDataView

        With newDataview
            .Sort = "utcDateTime DESC"
            .RowFilter = "IdTank = " & r("Id").ToString
        End With

        With newGrid
            .Name = "dg" & r("tankShortCode").ToString
            .DataSource = newDataview
        End With

        With newTab
            .Name = r("tankShortCode").ToString
            .Text = r("tankShortCode").ToString
            .Controls.Add(newGrid)
        End With

        With Me.tabTankTable

            .TabPages.Add(newTab)

        End With

        'End If
    Next

这实质上是在每个标签页上插入一个正确的DataGridView,并将相关过滤器应用于DataGridView。

然而,挑战在于我想要隐藏每个数据网格视图的前3列。但是当我尝试在DataGridView对象(即' newGrid')上执行此操作时,它不允许我这样做,因为' newGrid'对象似乎没有任何列?

我已经尝试了几种途径但是没有能够产生预期的结果。

在我看来,有两种选择:

  1. 找出为什么' newGrid'尽管数据源包含正确的数据(更新/刷新??),但对象没有列
  2. 在添加实际控件后捕获添加的控件并修改列。我也试过了这个,但得到了一个列索引错误,表明Control对象也没有列。
  3. 但是在查看表单时,所有dgViews都包含相应的数据并且都有列?

    有什么建议吗?

    Martijn Tholen

1 个答案:

答案 0 :(得分:2)

由于列是自动生成的,因此会在.DataSource设置后添加 添加DataBindingComplete事件处理程序,您可以在其中隐藏/删除列

With newGrid
    .Name = "dg" & r("tankShortCode").ToString
    .DataSource = newDataview
    AddHandler .DataBindingComplete, AddressOf Me.DataGridView_DataBindingComplete
End With

创建事件处理程序

Private Sub DataGridView_DataBindingComplete(sender As Object, e AsDataGridViewBindingCompleteEventArgs)
    Dim dgv As DataGridView = TryCast(sender, DataGridView)
    If dgv Is Nothing Then Exit Sub
    For Each column As DataGridViewColumn In dgv.Columns.Cast(Of DataGridViewColumn).Take(3)
        column.Visible = false
    Next

End Sub