簡體   English   中英

在vb.net的屏蔽文本框中插入空數據時如何做條件

[英]How to make conditions when inserting empty data in masked text box in vb.net

在使用帶遮罩的文本框插入日期時,我嘗試設置3個條件。 我要插入到數據庫中的數據是護照日期,這不是必須插入的數據,因為並非所有用戶都具有護照。 第一個條件是當有用戶將護照日期留空時,空數據將被保存到數據庫中。 秒條件是當用戶插入的日期不正確,例如“ 29/02/2019”時,將顯示一個消息框。 最后,當用戶輸入正確的日期時,數據將被保存到數據庫中。

我已經使用“ textbox.Text.Trim()。Length = 0”的語法,但該條件不起作用。

Private Sub insert_Click(sender As Object, e As EventArgs) Handles insert.Click

    'insert syntax
    Dim insert_command As New MySqlCommand("INSERT INTO employee(StaffID, StaffName, ExpiredDate1) _
    VALUES (@StaffID, @StaffName, @ExpiredDate1)", connection)

    'insert staffid
    If staffid.Text.Trim().Length > 0 Then
        insert_command.Parameters.Add("@StaffID", MySqlDbType.VarString).Value = staffid.Text
    End If

    'insert staffname
    If staffname.Text.Trim().Length = 0 Then
        insert_command.Parameters.Add("@StaffName", MySqlDbType.VarString).Value = DBNull.Value
    Else
        insert_command.Parameters.Add("@StaffName", MySqlDbType.VarString).Value = staffname.Text
    End If

    'insert passport date
    Dim dob As Date   

    If edate1.Text.Trim().Length = 0 Then
        insert_command.Parameters.Add("@ExpiredDate1", MySqlDbType.VarString).Value = DBNull.Value
    ElseIf Date.TryParse(edate1.Text, dob) Then
        insert_command.Parameters.Add("@ExpiredDate1", MySqlDbType.VarString).Value = edate1.Text
    Else
        MessageBox.Show("Invalid passport date", "Invalid Information", MessageBoxButtons.OK, _
        MessageBoxIcon.Exclamation)
    End If
End Sub

我得到的錯誤是當用戶確實將日期掩碼文本框保留為空時,它沒有插入空數據,而是讀取了最后一個條件。 我希望用戶能夠在不顯示最后一個條件msgbox的情況下將空數據插入數據庫。

在Visual Studio中,我可以在此行之前放置一個斷點

If edate1.Text.Trim().Length = 0 Then

然后,當我在“調試”模式下執行代碼並單擊表單上的按鈕時,可以將鼠標懸停在.Text函數上,以查看文本字段包含的內容。

因為我還沒有輸入任何內容,所以顯示為" / /" 顯然,即使是空值也有掩碼,因此.Length = 0將不起作用。

最簡單的方法是檢查該字段是否仍具有該默認值,但是如果更改了掩碼,則可能會導致問題。

當我將鼠標懸停在edate1變量上時(雖然仍在斷點處暫停),我可以選擇一個下拉菜單,向我顯示該變量的所有屬性和方法。 我注意到它有一個'MaskFull'和'MaskCompleted'可能有用(完整的列表也可以在.Net Docs中看到)。

讓我們測試一下:

If Not edate1.MaskFull Then
    Debug.Print("Not full")
ElseIf Date.TryParse(edate1.Text, dob) Then
    Debug.Print("Date!")
Else
    Debug.Print("Not full, no date")
End If

輸出量

  • " / /" “未滿”。

  • "01/01/197" '未滿'。

  • "01/01/1970" “日期!”。

  • "12/34/1970" “未滿,沒有日期”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM