我有一个包含两列C1和C2的数据表。(C1有AllowDBNull = false)。datatable的创建方式如下:
Private Function GetDataTable() As DataTable
Dim DT As New DataTable
'Create the first column
Dim C As New DataColumn("C1")
C.AllowDBNull = False
DT.Columns.Add(C)
'Second column
DT.Columns.Add(New DataColumn("C2"))
Return DT
End Function
然后我有一个表单,其中有两个绑定到datatable的文本框:
Dim DT As DataTable = GetDataTable()
Dim CurrencyManager As CurrencyManager = CType(Me.BindingContext(DT), CurrencyManager)
'Add the bindings
TextBox1.BindingContext = Me.BindingContext
TextBox2.BindingContext = Me.BindingContext
TextBox1.DataBindings.Add(New Binding("text", DT, "C1", True, DataSourceUpdateMode.OnValidation))
TextBox2.DataBindings.Add(New Binding("text", DT, "C2", True, DataSourceUpdateMode.OnValidation))
'Set the null value of the Textbox1
TextBox1.DataBindings(0).NullValue = ""
我正在设置textBox1的NullValue,这样每当textbox是"“时,它就应该被视为DBNull。
我使用CurrencyManager插入一个新行:
'Insert a new row
CurrencyManager.AddNew()
'Fill the two columns...
Dim Row As DataRowView = CurrencyManager.Current
Row.Row.Item(0) = "Column 1 Value"
Row.Row.Item(1) = "Column 2 Value"
'Validate the entry
CurrencyManager.EndCurrentEdit() 'No issue here since
现在,当用户清除FirstTextBox (哪个datatable列具有AllowDBNull false)时,如果我运行两次以下代码。第一次出现异常时,msgbox会显示出来,但第二次不会引发异常值,取回之前的值“1value”,该列不再是dbnull。
Try
CurrencyManager.EndCurrentEdit()
Catch ex As Exception
msgbox("The field C1 can not be empty")
End Try
我的问题是:有没有办法让最后一段代码在字段为空时总是抛出异常?
干杯,
发布于 2018-05-31 10:56:51
假设我正确地理解了你的目标,那么像这样的东西应该是可行的。
Private Sub TextBox1_Validating(sender As Object, e As CancelEventArgs) Handles TextBox1.Validating
Try
CurrencyManager.EndCurrentEdit()
Catch ex As Exception
MsgBox("The field C1 can not be empty")
TextBox1.DataBindings(0).WriteValue() ' push the value to the datasource
e.Cancel = True
End Try
End Sub
编辑:我只想声明,不推荐使用异常进行验证,因为您可以在不使用异常的情况下轻松地验证文本。这还假设这可以放在验证事件中;这是我的一个假设,即可能是不正确的。
https://stackoverflow.com/questions/50613878
复制相似问题