User-939850651 posted
Hi MOHIMRAN,
If you need to check whether the data entered by the user is already contained in the database, you need to query the database accordingly.
You could try to use the
OnTextChanged event
or use Ajax to check the user input. Please refer to the following code:
OnTextChanged event:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox runat="server" ID="field1" OnTextChanged="field1_TextChanged" AutoPostBack="true"></asp:TextBox>
</div>
</form>
</body>
Protected Sub field1_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim fieldText As String = field1.Text
Dim conStr As String = ConfigurationManager.ConnectionStrings("conStr").ToString()
Using conn As SqlConnection = New SqlConnection(conStr)
Dim query As String = "Select * from testtbl where ItemName=@field"
Using cmd As SqlCommand = New SqlCommand(query, conn)
cmd.Parameters.AddWithValue("@field", fieldText)
Dim dt As DataTable = New DataTable()
Dim sda As SqlDataAdapter = New SqlDataAdapter(cmd)
sda.Fill(dt)
If dt.Rows.Count > 0 Then
' input data is exist
Response.Write("<script>console.log('Enter data exist in Database.')</script>")
field1.Text = String.Empty
Else
' input data not exist
Response.Write("<script>console.log('Enter data not exist')</script>")
End If
End Using
End Using
End Sub
Ajax:
<head runat="server">
<script src="Scripts/jquery-3.4.1.min.js"></script>
<title></title>
<script>
$(document).ready(function () {
$('input[id*=field1]').keyup(function () {
$.ajax({
url: 'Page.aspx/checkIfExist',
type: 'POST',
data: '{"param":"'+$(this).val()+'"}',
contentType: 'application/json',
success: function (response) {
console.log(response.d);
//check return result and do something here...
},
error: function () {
console.log('something wrong');
}
})
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox runat="server" ID="field1"></asp:TextBox>
</div>
</form>
</body>
<WebMethod>
Public Shared Function checkIfExist(ByVal param As String) As String
Dim conStr As String = ConfigurationManager.ConnectionStrings("conStr").ToString()
Using conn As SqlConnection = New SqlConnection(conStr)
Dim query As String = "Select * from testtbl where ItemName=@ItemName"
Using cmd As SqlCommand = New SqlCommand(query, conn)
cmd.Parameters.AddWithValue("@ItemName", param)
Dim dt As DataTable = New DataTable()
Dim sda As SqlDataAdapter = New SqlDataAdapter(cmd)
sda.Fill(dt)
If dt.Rows.Count > 0 Then
Return "Input data exist in Database." ' data exist
Else
Return "Input data not exist" ' not exist
End If
End Using
End Using
End Function
Result:

You can see that until I enter Item1, it will prompt me that the input data already exists. And the first method will cause the page to post back, I recommend the second method.
Best regards,
Xudong Peng