如何在 vb.net 中使用绑定源插入、更新和删除后维护 DataGridView 控件中的选定行

问题描述 投票:0回答:1

我正在尝试在 vb.net 中使用绑定源插入、更新和删除后维护 DataGridView 控件中的选定行。

我还使用了“DataBindingComplete”事件datagridview,但它不起作用,因为我的代码可能有问题。

例如,如果我在加载数据后通过按钮事件插入一条记录,则所选行将自动位于新记录位置;如果我在加载数据后通过按钮事件更新一条记录,则所选行将自动位于新记录位置更新记录位置,如果我在按钮事件中删除记录,则所选行位于已删除记录的上一条记录中。

请指导我

谢谢

 Dim CatProdService As New CatProdService()
    Private bindingSource As BindingSource = Nothing
    Private selectedOrder As String
    Private selectedIndex As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        LoadData1()
    End Sub
    Private Sub LoadData1()
        Dim CatProd = CatProdService.Getitem()
        bindingSource = New BindingSource With {.DataSource = New BindingList(Of CatProd)(CType(CatProdService.Getitem(), IList(Of CatProd)))}
        DataGridView1.DataSource = bindingSource
        DataGridView1.ReadOnly = True
    End Sub
    Private Function GetSELECT() As CatProd
        Return If(DataGridView1.SelectedCells.Count = 0, Nothing, TryCast(DataGridView1.SelectedCells(0).OwningRow.DataBoundItem, CatProd))
    End Function    

Private Sub DataGridView1_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles DataGridView1.DataBindingComplete
        If (Not String.IsNullOrEmpty(selectedOrder) _
            AndAlso (e.ListChangedType = ListChangedType.Reset)) Then
            If (bindingSource.List.Count > 0) Then
                selectedIndex = bindingSource.Find("CatProd", selectedOrder)
                If (selectedIndex <= 0) Then
                    selectedIndex = 0
                End If

                DataGridView1.Rows(selectedIndex).Selected = True
            Else
                selectedOrder = String.Empty
            End If

        End If

    End Sub
    Private Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles BtnDelete.Click
        Try
            Dim SelectDgv = GetSELECT()
            If MessageBox.Show("Delete selected record?", "CONFIRM!", MessageBoxButtons.YesNoCancel) = DialogResult.Yes Then
                CatProdService.DeleteItem(SelectDgv.ID)
                LoadData1()
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, "TEST", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub
  Private Sub Btnsave_Click(sender As Object, e As EventArgs) Handles Btnsave.Click
        Dim CatProd = CatProdService.GetByCatProd(txtCatProd.Text)
        Dim DesCatProd = CatProdService.GetByDesCatProd(txtDesCatProd.Text)
        Dim isValidID As Boolean
        Boolean.TryParse(btxtid.Text, isValidID)

        Dim userid2 = CatProdService.GetCatProdById2(CBool(isValidID))
        Try
            If txtCatProd.TextLength > 3 Then
                MessageBox.Show("CatProd Product Only 3 Characters or Digits")
                Return
            End If
            If userid2 Is Nothing Then
                If CatProd IsNot Nothing Then
                    MessageBox.Show("CatProd Product already exists")
                    Return
                End If
                If DesCatProd IsNot Nothing Then
                    MessageBox.Show("DesCatProd Product already exists")
                    Return
                End If

                If String.IsNullOrEmpty(txtCatProd.Text) OrElse String.IsNullOrEmpty(txtDesCatProd.Text) Then
                    MsgBox("Required fill CatProd,DesCatProd", MsgBoxStyle.Information, "Information")
                    Return
                End If
                'insert new record
                CatProdService.InsertCatProd(New CatProd() With {
            .CatProd = txtCatProd.Text,
            .DesCatProd = txtDesCatProd.Text
        })
            Else
                'Update record
                CatProdService.UpdateCatProd(New CatProd() With {
             .CatProd = txtCatProd.Text,
            .DesCatProd = txtDesCatProd.Text,
            .ID = CInt(btxtid.Text)
             })

            End If
            MessageBox.Show("Successfull")

            'btnOk.Enabled = False
            'btnOk.BackColor = Color.DarkGray
            LoadData1()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "TEST", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

        End Try
    End Sub

RESULT CODE 08102024

vb.net datagridview bindingsource bindinglist
1个回答
0
投票

您应该使用列表并将其作为数据源添加到绑定源组件。然后将绑定源组件作为数据源添加到网格中。这只需要做一次。

之后,只需管理列表中的所有内容,即添加/更新/删除,并在完成后刷新绑定。网格将更新并自动保留位置。

例如

Public Class Form1


Private fakeTeams As New List(Of Team)


Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    fakeTeams = CreateFakeTeams()
    gridTeams.DataSource = TeamBindingSource
    TeamBindingSource.DataSource = fakeTeams
End Sub

Private Sub bnAddNew_Click(sender As Object, e As EventArgs) Handles bnAddNew.Click
    fakeTeams.Add(New Team With {.Name = "New Team", .City = "New City", .League = "New League", .Division = "New Division"})
    TeamBindingSource.ResetBindings(False)
End Sub

Private Function CreateFakeTeams() As List(Of Team)
    Dim teams As New List(Of Team) From {
        New Team With {.Name = "Yankees", .City = "New York", .League = "American", .Division = "East"},
        New Team With {.Name = "Red Sox", .City = "Boston", .League = "American", .Division = "East"},
        New Team With {.Name = "Blue Jays", .City = "Toronto", .League = "American", .Division = "East"},
        New Team With {.Name = "Orioles", .City = "Baltimore", .League = "American", .Division = "East"},
        New Team With {.Name = "Rays", .City = "Tampa Bay", .League = "American", .Division = "East"}
    }
    Return teams
End Function

Private Sub bnRemove_Click(sender As Object, e As EventArgs) Handles bnRemove.Click
    Dim selectedRow = gridTeams.CurrentRow.Index
    fakeTeams.RemoveAt(selectedRow)
    TeamBindingSource.ResetBindings(False)
End Sub

End Class

Public Class Team

    Public Property Name As String
    Public Property City As String
    Public Property League As String
    Public Property Division As String

End Class
© www.soinside.com 2019 - 2024. All rights reserved.