【发布时间】:2023-03-06 02:08:01
【问题描述】:
我有一个包含两列 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
我的问题是:有没有办法让最后一个代码在字段为空时总是引发异常?
干杯,
【问题讨论】:
-
我发现您的命名约定令人困惑。
Dim CurrencyManager As CurrencyManager是数据类型还是实例变量?Dim Row As DataRowView = CurrencyManager.Current Row.Row.Item(0)看起来很奇怪。
标签: vb.net data-binding