首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >绑定和DBNull问题。异常仅引发一次

绑定和DBNull问题。异常仅引发一次
EN

Stack Overflow用户
提问于 2018-05-31 05:55:26
回答 1查看 93关注 0票数 0

我有一个包含两列C1和C2的数据表。(C1有AllowDBNull = false)。datatable的创建方式如下:

代码语言:javascript
复制
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的文本框:

代码语言:javascript
复制
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插入一个新行:

代码语言:javascript
复制
'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。

代码语言:javascript
复制
Try
    CurrencyManager.EndCurrentEdit()
Catch ex As Exception
    msgbox("The field C1 can not be empty")
End Try       

我的问题是:有没有办法让最后一段代码在字段为空时总是抛出异常?

干杯,

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-31 10:56:51

假设我正确地理解了你的目标,那么像这样的东西应该是可行的。

代码语言:javascript
复制
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

编辑:我只想声明,不推荐使用异常进行验证,因为您可以在不使用异常的情况下轻松地验证文本。这还假设这可以放在验证事件中;这是我的一个假设,即可能是不正确的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50613878

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档