You can use $('#HiddenField1').val(Name) to get the value in the TextBox and then loop through the GridView to compare it with the value in the HiddenField.
The code:
<script type="text/javascript">
$(document).ready(function () {
$('#txtName').blur(function () {
var Name = $('#txtName').val();
$('#HiddenField1').val(Name);
var a =1;
$("#<%=GridView1.ClientID%> tr td").each(function () {
if ($('#HiddenField1').val() == $(this).text()) {
alert("duplicate value")
a = 2;
}
})
if (a = 1) {
$('#Button1').click(function () {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'WebForm99.aspx/Insert_Data',
data: "{'Name':'" + Name + "'}",
async: false,
success: function () {
$("#GridView1 tbody").append("<tr><td>" + $('#txtName').val() + "</td></tr>")
$('#txtName').val("");
},
});
})
}
});
});
</script>
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:HiddenField ID="HiddenField1" runat="server"/>
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
</asp:GridView>
<input type="button" id="Button1" value="Save" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CaseTestConnectionString %>" SelectCommand="SELECT [Name] FROM [Test14]"></asp:SqlDataSource>
</div>
Aspx.cs:
[WebMethod]
public static void Insert_Data(string Name)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["constr527"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("Insert into Test14 (Name) values(@Name)", conn);
cmd.Parameters.AddWithValue("@Name", Name);
cmd.ExecuteNonQuery();
conn.Close();
}
The result:
Best regards,
Sam
IIS.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today. Learn more >
Contributor
3370 Points
1409 Posts
Re: gridview no duplicate value should be entered
Jun 25, 2019 08:52 AM|samwu|LINK
Hi geetasks,
You can use $('#HiddenField1').val(Name) to get the value in the TextBox and then loop through the GridView to compare it with the value in the HiddenField.
The code:
The result:
Best regards,
Sam