vb.net - 绑定和 DBNull 问题。异常只引发一次
问题描述
我有一个包含两列 C1 和 C2 的数据表。(C1 有 AllowDBNull = false)。数据表创建如下:
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
然后我有一个表单,其中有两个文本框绑定到数据表:
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,这样每当文本框为“”时,它都应被视为 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(其中数据表列的 AllowDBNull 为 false)时。第一次引发异常并显示 msgbox,但是第二次它没有引发异常并且它取回之前的值,即“列 1 值”并且该列不再是 dbnull。
Try
CurrencyManager.EndCurrentEdit()
Catch ex As Exception
msgbox("The field C1 can not be empty")
End Try
我的问题是:当字段为空时,有没有办法让最后一个代码总是引发异常?
干杯,
解决方案
假设我正确理解了您的目标,那么这样的事情应该可以工作。
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
编辑:我只想声明不建议使用这种异常进行验证,因为您可以轻松验证文本而不使用异常。这也假设这可以放在验证事件中;我的一个假设是我是不正确的。
推荐阅读
- django - 如何在 django-admin 上过滤模型
- excel - 为顶行和最后一列着色的宏
- javascript - 如何使用javascript修复错误“未捕获的引用错误:未定义数据”?
- python - 对 Pandas 数据框中的组进行 T 检验以获取唯一 ID
- mysql - 无法链接驱动程序 rlm_sql_mysql
- winforms - 从 CliXml PS 加载 WinForm 对象
- ruby - `nil` 可以在`case/when` 语句中匹配,并带有显式的`when nil` 分支?
- android - 保护 API 仅供特定应用程序使用
- r - 使用 geom_text 函数时的几个标签
- google-cloud-platform - GKE 负载均衡器只能从 Cloud Shell 访问