有时,当您在不关闭程序的情况下重新加载表单时,第一行将突出显示。但它不会被选中,你会得到 -1 选定的行索引。
你可以这样做:
1. 表单加载时存储默认样式:
Public Class aRoots
Dim df1, df2, df3, df4 As Color
Private Sub aRoots_Load(sender As Object, e As EventArgs) Handles Me.Load
df1 = DGV_Root.DefaultCellStyle.SelectionBackColor
df2 = DGV_Root.DefaultCellStyle.BackColor
df3 = DGV_Root.DefaultCellStyle.SelectionForeColor
df4 = DGV_Root.DefaultCellStyle.ForeColor
2.与datagridview交互时改变cell样式:
Private Sub LoadRoot()
For i = 0 To 5
DGV_Root.Rows.Add()
For j = 0 To 3
DGV_Root.Item(j, i).Value = ...
Next
Next
'DGV_Root.ClearSelection() ==> instead of this use 2 lines below
DGV_Root.DefaultCellStyle.SelectionBackColor = df2
DGV_Root.DefaultCellStyle.SelectionForeColor = df4
End Sub
3. 当像 cell_click 或 cell_double click 改变选择时,将单元格样式更改为默认值:
Private Sub DGV_Root_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DGV_Root.CellMouseClick
DGV_Root.DefaultCellStyle.SelectionBackColor = df1
DGV_Root.DefaultCellStyle.SelectionForeColor = df3
...
End Sub
4.当你想关闭表单时,全部恢复为默认值:
Private Sub PbClose_Click(sender As Object, e As EventArgs) Handles PbClose.Click
BtnCancel.PerformClick()
DGV_Root.DefaultCellStyle.SelectionBackColor = df1
DGV_Root.DefaultCellStyle.BackColor = df2
DGV_Root.DefaultCellStyle.SelectionForeColor = df3
DGV_Root.DefaultCellStyle.ForeColor = df4
Me.Close()
End Sub
希望这对你们有帮助。