在运行时创建多个datagridview控件时,如何隐藏列?

时间:2012-12-06 23:30:49

标签: sql-server vb.net datagridview tabcontrol datagridviewcolumn

我在运行时生成的datagridview控件中隐藏列时遇到了一些麻烦。我在现有选项卡控件中的运行时生成的选项卡页面内生成该控件。我的代码如下:

Try
    Do
        If m_DataTable.Columns.Contains("Checkpoint " & intCheckPointNumber & " Time") Then
            Dim tabNewCheckpoint As New TabPage
            Dim dgvNewCheckpoint As New DataGridView

            tabNewCheckpoint.Name = "tabCheckpoint" & intCheckPointNumber
            tabNewCheckpoint.Text = "Checkpoint " & intCheckPointNumber
            tabctrlTimingTable.TabPages.Add(tabNewCheckpoint)

            dgvNewCheckpoint.Name = "dgvCheckpoint" & intCheckPointNumber
            dgvNewCheckpoint.DataSource = m_DataTable
            dgvNewCheckpoint.Size = dgvTimingP2P.Size
            tabNewCheckpoint.Controls.Add(dgvNewCheckpoint)

            Try
                strColumnName = "Checkpoint " & intCheckPointNumber
                For Each col As DataColumn In m_DataTable.Columns
                    MessageBox.Show(col.ColumnName)
                    If col.ColumnName.StartsWith("Checkpoint") Then
                        If Not col.ColumnName.StartsWith(strColumnName) Then
                            dgvNewCheckpoint.Columns(col.ColumnName).Visible = False
                        End If
                    End If
                Next
            Catch
                MessageBox.Show(ErrorToString)
            End Try
        Else
            Exit Do
        End If
        intCheckPointNumber += 1
    Loop
Catch ex As Exception
    'MessageBox.Show(ErrorToString)
End Try

col.ColumnName值直接对应于数据库中的列,但在此行上会立即生成错误:

dgvNewCheckpoint.Columns(col.ColumnName).Visible = False

我不断得到的错误是:“对象引用未设置为对象的实例”

此代码适用于我在选项卡控件中的另一个标签页内部的datagridview控件,它们都是在设计时创建的。

在创建运行时生成的datagridview后立即尝试隐藏列是否有问题?

我正在使用VB2010。

我最初使用以下代码:

For Each col As DataGridViewColumn In dgvNewCheckpoint.Columns
MessageBox.Show(col.Name)
    If col.Name.StartsWith("Checkpoint") Then
        If Not col.Name.StartsWith(strColumnName) Then
            col.Visible = False
        End If
    End If
Next

我在这里遇到的问题是,程序跳过这个For ... Next循环,因为它一定不能在dgvNewCheckpoint datagridview控件中看到DataGridViewColumns。当我更改它以引用数据库中的列时,我实际上得到了结果。我在这里错误地引用了这些列吗?

1 个答案:

答案 0 :(得分:1)

在绑定到数据表之前,应将DGV添加到控制列表中。因此,该行应移动如下:

Dim tabNewCheckpoint As New TabPage
Dim dgvNewCheckpoint As New DataGridView

tabNewCheckpoint.Name = "tabCheckpoint" & intCheckPointNumber
tabNewCheckpoint.Text = "Checkpoint " & intCheckPointNumber
tabctrlTimingTable.TabPages.Add(tabNewCheckpoint)

tabNewCheckpoint.Controls.Add(dgvNewCheckpoint) 'This is the line to be moved

dgvNewCheckpoint.Name = "dgvCheckpoint" & intCheckPointNumber
dgvNewCheckpoint.DataSource = m_DataTable
dgvNewCheckpoint.Size = dgvTimingP2P.Size