locked
validate if value is in database RRS feed

  • Question

  • User1717218719 posted

    Hi All

    I have a textbox ehich gets results from the database base on the value entered into the textbox.  I am looking to do a validation check. eg. if value entered in textbox is in sql database then write "Error: Invalid Value". I am not sure how to go about this in Vb

    any help would be great

    Thanks

    Monday, August 19, 2019 8:17 AM

Answers

  • User288213138 posted

    Hi E.RU,

    According to your description, I made a demo for your reference.

    You can use Ado.net to query the values in the database, and then compare the values of the textbox with the data that you query.

    The code:

    <div>
                Check from database:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
                <asp:Button ID="Button1" runat="server" Text="Check" OnClick="Button1_Click" /><br />
                <asp:Label ID="Label1" runat="server"></asp:Label>
            </div>
    
    Private flage As Boolean = False
    
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    
            Using con As SqlConnection = New SqlConnection(constr)
    
                Using cmd As SqlCommand = New SqlCommand("SELECT CustomerId FROM Customer where Name='n1'")
                    cmd.Connection = con
                    con.Open()
                    Dim sdr As SqlDataReader = cmd.ExecuteReader()
    
                    While sdr.Read()
    
                        If sdr(0).ToString() = TextBox1.Text Then
                            flage = True
                            Exit While
                        End If
                    End While
    
                    If flage = True Then
                        Label1.Text = "Invalid Value"
                    Else
                        Label1.Text = "valid Value"
                    End If
                End Using
            End Using
    End Sub
    

    The result:

    Best regards,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 20, 2019 2:18 AM