第一次填充我的datagridview时,它会突出显示第一行,并且我有一个按钮,当单击该按钮时,会显示所单击的索引的值,因此我知道单击了哪一行。如果用户进行另一次搜索,我清除datagridview的内容,然后用新数据重新填充它。同样,第一行(索引(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”,如果数据网格重新填充新数据,那么下次点击按钮时我会收到错误。
感谢您的帮助。
答案 0 :(得分:4)
除了在数据刷新后设置所选行之外,还应设置将自动设置CurrentRow
属性的当前单元格。所以,例如:
.Rows(0).Selected
.CurrentCell = .Rows(0).Cells(0)