我有一个填充数据表的 SQL Server 数据库,该数据表是 datagridview 控件的数据源。我想隐藏 datagridview 控件中以字符串开头的所有列:
strColumnName = "Checkpoint " & intCheckpointNumber
我怎样才能做到这一点?我正在使用 VB2010。
我结束的地方,显然不起作用的是以下内容:
Do While intCheckpoint < intTotalCheckPoints
If Me.datagridview.Columns ' I cannot figure out how to insert something along the lines of Name.StartsWith(strColumnName)' Then
'Hide this column with something along the lines of 'Me.datagridview.Columns(strColumnName).Visible = False
End If
intCheckPoint += 1
Loop
我不知道如何根据它们的名称开头隐藏列。
谢谢
好的,我已经修改了我的代码,结果如下:
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)
strColumnName = "Checkpoint " & intCheckPointNumber
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
Else
Exit Do
End If
intCheckPointNumber += 1
Loop
Catch ex As Exception
'MessageBox.Show(ErrorToString)
End Try
我现在遇到的问题是这些列仍然没有隐藏。如果我在程序中插入停止,我可以看到代码甚至没有处理 For...Next 循环。什么会导致这个?
谢谢
好的,现在我已经改变了:
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 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
它给了我一个错误:“对象引用未设置为对象的实例”,但 datagridview 列与数据表列具有相同的名称,所以我看不出这是怎么可能的。有任何想法吗?