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


    Monday, August 19, 2019 8:17 AM


  • 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:

                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>
    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
                    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"
                        Label1.Text = "valid Value"
                    End If
                End Using
            End Using
    End Sub

    The result:

    Best regards,


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