保持datagridview行处于选中状态

保持datagridview行处于选中状态,datagridview,Datagridview,在从数据库读取信息后,我希望有一个datagridview行保持选中状态,但它总是返回到第1行。如果我删除dt.clear,我可以选择相同的行,但数据会不断重复 Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Dim row As Integer If DataGridView1.Rows.Count > 0 Then row = DataGridVi

在从数据库读取信息后,我希望有一个datagridview行保持选中状态,但它总是返回到第1行。如果我删除dt.clear,我可以选择相同的行,但数据会不断重复

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Dim row As Integer
    If DataGridView1.Rows.Count > 0 Then
        row = DataGridView1.CurrentRow.Index
    End If
    dt.Clear()
    Try
        con.Open()
        sql = "Select * from Requests"
        cmd.Connection = con
        cmd.CommandText = sql
        da.SelectCommand = cmd
        da.Fill(dt)
        DataGridView1.DataSource = dt
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        con.Close()
    End Try
    If DataGridView1.Rows.Count > 0 Then
        DataGridView1.Rows(row).Selected = True
    End If
End Sub

我必须问一下,我不是想告诉你怎么做,但是,不管
计时器的值是多少。Interval
设置为…使用
计时器查询数据库并不一定是最好的方法,就像你发布的代码那样。您能否澄清您希望/需要使用
计时器更新网格的“原因”

此外,强烈建议代码至少对连接使用
use
语句,以确保连接正确关闭

您当前的问题是代码需要设置网格的grids
CurentCell
属性以设置“选定”单元格/行,您可以使用当前代码执行此操作,但是您不知道“哪个单元格/列”设置为CurrentCell,除非在更改网格的数据源之前获取网格
CurrentCell

您可以将计时器滴答声事件末尾的代码更改为

DataGridView1.CurrentCell = DataGridView1.Rows(row).Cells(0)
实现你的要求;但是,此代码正在将列(0)设置为当前单元格,它可能是列(4)或其他列

在更改网格的数据源之前,需要获取网格的
CurrentCell
行和列索引。然后,在网格的数据源发生更改后…将网格的
CurrentCell
属性设置为以前获取的索引。如下所示

如果您必须为此使用
计时器
,那么我建议使用一种稍微不同的方法,如下所示。它仍然可以被清理;但是,正如我在评论中建议的那样,代码确实使用了
语句来实现

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
  Dim row = DataGridView1.CurrentCell.RowIndex
  Dim col = DataGridView1.CurrentCell.ColumnIndex
  GetDataFillGrid()
  If DataGridView1.Rows.Count > row And DataGridView1.Columns.Count > col Then
    DataGridView1.CurrentCell = DataGridView1.Rows(row).Cells(col)
  End If
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  GetDataFillGrid()
  Timer1.Start()
End Sub

Private Sub GetDataFillGrid()
  Dim conString = "YourConnectionString"
  Dim Sql = "YourQueryString"
  Dim dt = New DataTable
  Try
    Using con As New SqlConnection(conString)
      con.Open()
      Using cmd As New SqlCommand(Sql, con)
        Using da As New SqlDataAdapter(cmd)
          da.Fill(dt)
          DataGridView1.DataSource = dt
        End Using
      End Using
    End Using
  Catch ex As Exception
    MessageBox.Show("Error: " + ex.Message)
  End Try
End Sub

首先,非常感谢您抽出时间!恢复我试图实现的是创建两个连接到同一数据库的应用程序,一个用于发出中断等请求,另一个用于批准它们(我遇到的问题)。我已经尝试过你的解决方案,但仍然有错误。正如你可能已经了解的那样,我是一个傻瓜,我只是玩玩而已。我贴出了这个问题,希望是简单的,不要浪费更多的时间,我会继续玩。再次感谢您的回复和时间@安东尼奥·罗马诺。。。听起来你好像忙得不可开交。很抱歉,您收到错误,在我的测试中,我发布的代码按预期工作。在未来……了解您得到的确切“错误/错误消息”会有所帮助。。。对于试图帮助您修复这些错误的人来说,像“它不工作”或“它有错误”这样的评论并不重要,但是,这似乎并不重要。祝你好运。不要误会我,我感谢你的帮助我没有深入了解你代码中的错误,因为我不想把你更多的时间花在一些我只是在玩的东西上,而且它真的不重要:)非常感谢约翰!