【问题标题】:Set column visibility (properties) of added datagridview prior to adding the control to the form在将控件添加到表单之前设置添加的 datagridview 的列可见性(属性)
【发布时间】:2015-08-26 13:15:12
【问题描述】:

GD 全部,

我有一个相当简单的表单的循环,它为选择的记录添加标签页。在添加的选项卡上,它插入一个 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。

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

我尝试了几种途径,但都无法产生预期的结果。

在我看来有两种选择:

  1. 找出为什么“newGrid”对象没有列,尽管数据源包含正确的数据(更新/刷新??)
  2. 在添加实际控件后捕获添加的控件并修改列。我也尝试过,但出现列索引错误,表明 Control 对象也没有列。

然而,在查看表单时,所有 dgView 中都有适当的数据并且都有列?

有什么建议吗?

马丁·托伦

【问题讨论】:

    标签: vb.net winforms datagridview


    【解决方案1】:

    因为列是自动生成的,它们将在设置.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-11
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      相关资源
      最近更新 更多