DataGridView 如何在 VB.NET 中的事件填充后保留所选行的位置。
我想在不使用BindingSource的情况下是否可以应用,请指导。
对于数据库信息,表没有ID,但有4列主键,分别是:CODEPRODUCT,BARCODE,COLORCODE,SIZE
谢谢
Private WithEvents dt As New DataTable
Dim dataAdapter As OleDbDataAdapter
Dim GetConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\demo.accdb;Persist Security Info=False;"
Private Sub population()
Try
dt = New DataTable
Dim query As String = "SELECT * from stocks"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
Using da As New OleDbDataAdapter(cmd)
'Dim dt As DataTable = New DataTable()
da.Fill(dt)
da.Dispose()
DataGridView1.DataSource = dt
Me.DataGridView1.Refresh()
End Using
End Using
End Using
Catch ex As Exception
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
Me.DataGridView1.MultiSelect = False
population()
End Sub
Private Sub Btnrefresh_Click(sender As Object, e As EventArgs) Handles Btnrefresh.Click
population()
End Sub
datagridview 的结果为 19082023
我们感谢他们为我们提供了最好的解决方案
根据@RezaAghaei的解决方案 这是一个链接!
并且根据@R.Akhlaghi的解决方案 这是一个链接!
我尝试了他们的代码组合终于得到了解决方案。
Private pk1 As String
Private pk2 As String
Private pk3 As String
Private pk4 As String
Private Sub Btnrefresh_Click(sender As Object, e As EventArgs) Handles Btnrefresh.Click
Dim currentIndex As Integer = DataGridView1.CurrentRow.Index
pk1 = DataGridView1.SelectedRows(0).Cells(0).Value
pk2 = DataGridView1.SelectedRows(0).Cells(1).Value
pk3 = DataGridView1.SelectedRows(0).Cells(2).Value
pk4 = DataGridView1.SelectedRows(0).Cells(3).Value
scrollIndex = DataGridView1.FirstDisplayedScrollingRowIndex
IsSelectedRow = True
population()
Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(currentIndex).Cells(0)
End Sub
Private Sub DataGridView1_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles DataGridView1.DataBindingComplete
If IsSelectedRow Then
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(0).Value.ToString().Equals(pk1.ToString()) AndAlso row.Cells(1).Value.ToString().Equals(pk2.ToString()) AndAlso row.Cells(2).Value.ToString().Equals(pk3.ToString()) AndAlso row.Cells(3).Value.ToString().Equals(pk4.ToString()) Then
rowIndex = row.Index
Exit For
End If
Next row
DataGridView1.Rows(rowIndex).Selected = True
End If
End Sub