绑定和DBNull问题。例外情况只提出一次

时间:2018-05-30 21:55:26

标签: vb.net data-binding

我有一个带有两列C1和amp;的数据表。 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(哪个datatable列的AllowDBNull为false)时,如果我运行以下代码两次。 第一次引发异常并显示msgbox,但第二次没有引发异常,它会收回之前的值,即& #34;第1列价值"并且该列不再是dbnull。

Try
    CurrencyManager.EndCurrentEdit()
Catch ex As Exception
    msgbox("The field C1 can not be empty")
End Try       

我的问题是:当字段为empy时,有没有办法让最后一个代码总是引发异常?

干杯,

1 个答案:

答案 0 :(得分:0)

假设我正确理解你的目标,那么这样的事情应该有用。

your_email = forms.EmailField(help_text='Enter a valid email.', 
 widget=forms.TextInput(attrs={'placeholder':'please enter a valid email'}))

编辑:我只是想声明不建议使用异常进行验证,因为您可以轻松验证文本而不使用异常。这也假定这可以放在验证事件中;我个人认为我的错误。

相关问题