我第一次填充我的 datagridview 时,它突出显示了第一行,并且我有一个按钮,单击该按钮时会显示被单击的索引的值,因此我知道单击了哪一行。如果用户进行另一次搜索,我会清除 datagridview 的内容,然后用新数据重新填充它。同样,第一行 (index(0)) 被突出显示,但是这一次,当用户单击按钮时,即使网格的第一行被突出显示,我得到一个错误,表明 data_grid.rows 什么都不是。我尝试将第一行设置为 .selected = true,但这并没有改变任何东西。它只在第一次起作用,然后就再也不起作用了。这是我的代码:
Public sub show_data()
' Clear everything out of the data grid
' -------------------------------------
With data_grid
While data_grid.RowCount > 0
data_grid.Rows.Clear()
End While
While data_grid.ColumnCount > 0
data_grid.Columns.Clear()
End While
End With
' add the empty rows to the data grid
' -----------------------------------
Dim rows As Integer = assessment_array.Count()
data_grid.Rows.Add(rows)
' Add the data to the columns
' ---------------------------
For r As Integer = 0 To rows - 1
data_grid.Item(0, r).Value = assessment_array(r)(0)
data_grid.Item(1, r).Value = assessment_array(r)(1)
data_grid.Item(2, r).Value = assessment_array(r)(2)
Next
With data_grid
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
.RowHeadersVisible = False
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
.AllowUserToOrderColumns = True
.ReadOnly = True
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.MultiSelect = False
.AllowUserToResizeRows = False
.Rows(0).Selected = True ' highlight the first row
End With
End sub
AddHandler myButton.Click, AddressOf check_for_highlighted_assessment
Public Sub check_for_highlighted_assessment()
MessageBox.Show(data_grid.CurrentRow.Index.ToString)
End Sub
第一次单击按钮时,我得到“0”,如果数据网格重新填充了新数据,那么下次单击按钮时出现错误。
谢谢你的帮助。