Datagridview 在填充数据源后不自动 select 第一行

Datagridview doesnt auto select first row after filling datasource

我有 4 列的数据网格视图 [Nam] , [ID] , [Shuru] , [Payan] 第二列 ([ID]) 是隐藏的,用于收集有关数据的一些详细信息。 这是加载代码:

Private Sub SalMali_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.DGV_SalMaliTableAdapter.Fill(Me.FDBDataSet.DGV_SalMali)
End Sub

检索 DGV_SalMali table 中的所有内容。 我知道 datagridview 会在填充后自动选择第一行,所以我在 Selection Change 中放置了一个函数来检索数据。这是代码:

    Private Sub DGV_SalMaliDataGridView_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_SalMaliDataGridView.SelectionChanged
        refreshDT()
    End Sub
Public Sub refreshDT()
        Dim cnt As Integer = DGV_SalMaliDataGridView.Rows.Count
        If cnt = 0 Then
            GoTo line
        End If

        unlockAll()

        Dim sel As String = DGV_SalMaliDataGridView.SelectedRows(0).Cells(1).Value

        Dim dt As New DataTable
        dt = SalMaliTA.GetData_SalMali_B_ID(sel)
        Dim dtr As DataRow = dt.Rows(0)

        TextBox1.Text = dtr.Item(4)
        MaskedTextBox1.Text = mc.MtoS(dtr.Item(1))
        MaskedTextBox2.Text = mc.MtoS(dtr.Item(2))
        CheckBox1.Checked = dtr.Item(3)

        Exit Sub
line:
        lockAll()
    End Sub

但是当我调用 refreshDT() 时,选择不再有效。它在 refreshDT()

的第 8 行抛出错误

sub { exactly here : Dim sel As String = DGV_SalMaliDataGridView.SelectedRows(0).Cells(1).Value }

Thrown: "Index was out of range. Must be non-negative and less than the size of the collection." (System.ArgumentOutOfRangeException) Exception Message = "Index was out of range. Must be non-negative and less than the size of the collection.", Exception Type = "System.ArgumentOutOfRangeException"

datagridview 有行,我不知道是什么问题。 感谢您的帮助。

您目前正在检查是否有任何行但没有任何选定的行:

Public Sub refreshDT()
    Dim cnt As Integer = DGV_SalMaliDataGridView.Rows.Count
    If cnt = 0 Then
        lockAll()
        Exit Sub
    End If

    If DGV_SalMaliDataGridView.SelectedRows.Count = 0 Then
        DGV_SalMaliDataGridView.Rows(0).Selected = true
    End If

    unlockAll()

    Dim sel As String = DGV_SalMaliDataGridView.SelectedRows(0).Cells(1).Value

    Dim dt As New DataTable
    dt = SalMaliTA.GetData_SalMali_B_ID(sel)
    Dim dtr As DataRow = dt.Rows(0)

    TextBox1.Text = dtr.Item(4)
    MaskedTextBox1.Text = mc.MtoS(dtr.Item(1))
    MaskedTextBox2.Text = mc.MtoS(dtr.Item(2))
    CheckBox1.Checked = dtr.Item(3)
End Sub