用DataGridView.currentRow取值和用bindingsource.Current()取值的一些注意事项

本文介绍在使用DataGridView控件时如何正确地捕捉行变化事件。文章提供了两种方法:一种是使用CurrentCellChanged事件来响应行的变化,并通过currentSourcePosition变量进行控制;另一种是使用Bindingsource的CurrentChanged事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当希望在DataGridView行变化做一些动作,比如当前行的图片,控制等等...
不要使用bindingsource 的类似 "PositionChanged"、"CurrentChanged"、"CurrentItemChanged"等事件,当用这种事件获得DataGridView中的值还是上一条的值(后证实是使用方法不对,呵呵...最后将会列出方法)
而要改用DataGridView 的 CurrentCellChanged 事件,只是这个事件有一个弊端是当列改变是也是有效的(小控制一下就行,如下面用currentSourcePosition去控制
如下code
dim currentSourcePosition = 0
Private Sub POSSALESLINEDataGridView_CurrentCellChanged( _
                                                                         ByVal sender As Object, _
                                                                         ByVal e As System.EventArgs) _
                                                                         Handles POSSALESLINEDataGridView.CurrentCellChanged
        If _formStatus = formStatus.Loaded _
            And Me._sourceStatus = sourceStatus.POSSalesLine _
            And currentSourcePosition <> POSSALESTABLEPOSSALESLINEBindingSource.Position Then
            Dim _itemId As String = POSSALESLINEDataGridView.CurrentRow.Cells(1).Value
            Dim _lineNum As Integer = POSSALESLINEDataGridView.CurrentRow.Cells(0).Value
            Dim _fileName As String
            _fileName = findPicPath(_itemId)
            picItem = LoadImage(picItem, _fileName)

            currentSourcePosition = POSSALESTABLEPOSSALESLINEBindingSource.Position

        End If

    End Sub

 

 

使用Bindingsource_CurrentChange的方法

 

Private Sub InventTableBindingSource_CurrentChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles InventTableBindingSource.CurrentChanged
        If _formStatus = formStatus.Loaded Then
            Dim _itemId As String = InventTableMyDataGridView.CurrentRow.Cells(0).Value
            Dim _position As Integer = InventTableBindingSource.Position
            Dim _itemId2 As String = InventTableBindingSource.Current(1).ToString()
            MessageBox.Show("ItemId:" & _itemId & " -  ItemId 2: " & _itemId2 & " - position:" & _position)
        End If

    End Sub

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值