VB.NET中同一窗体兼具查看/编辑时如何禁用DataGridView RowValidating事件
解决方案
在FormTransaction中添加模式标识字段区分操作模式,在RowValidating事件中根据标识决定是否执行校验逻辑即可解决问题:
修改后的FormTransaction代码
Public Class FormTransaction Private list As New List(Of Product)() From { New Product With { .Codeproduct = "1000", .Qty = 20, .Qty_Stock = 0 }, New Product With { .Codeproduct = "2000", .Qty = 30, .Qty_Stock = 40 } } Private listnew As New List(Of Product)() ' 新增模式标识字段,默认处于添加模式 Private IsViewEditMode As Boolean = False Public Sub New() InitializeComponent() Dim bindingList As New BindingList(Of Product)(CType(listnew, IList(Of Product))) Dim source = New BindingSource(bindingList, Nothing) DataGridView1.DataSource = source End Sub Public Sub New(Invno As Product) Me.New() ' 切换为查看/编辑模式 IsViewEditMode = True DataGridView1.DataSource = list End Sub Private Sub DataGridView1_RowValidating(sender As Object, e As DataGridViewCellCancelEventArgs) Handles DataGridView1.RowValidating ' 查看/编辑模式下直接跳过校验逻辑 If IsViewEditMode Then Return Dim transferredQTY As Integer Dim onHandQTY As Integer With DataGridView1.Rows(e.RowIndex) Try transferredQTY = Convert.ToInt32(.Cells("Qty").Value) Catch ex As Exception transferredQTY = 0 End Try Try onHandQTY = Convert.ToInt32(.Cells("Qty_Stock").Value) Catch ex As Exception onHandQTY = 0 End Try If transferredQTY > onHandQTY Then MessageBox.Show("Please check don't Have sufficient quantity Stock" & "Only have Stock " & onHandQTY & " Pcs", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error) e.Cancel = True End If End With End Sub End Class
修改说明
- 新增
IsViewEditMode私有字段,默认值为False,对应添加模式 - 在带参数的构造函数(查看/编辑模式入口)中,将
IsViewEditMode设为True - 在
RowValidating事件开头增加判断:如果处于查看/编辑模式,直接退出事件,不执行库存校验逻辑
修改后,点击BtnViewEdit打开窗体时不会触发库存不足的错误提示;点击BtnAdd时,库存校验逻辑正常生效。
内容的提问来源于stack exchange,提问作者user22579796
相关产品推荐
相关产品推荐

