Home > ASP.Net, Javascript > Validate CheckBox in GridView (at least one checked) using JavaScript in ASP.Net

Validate CheckBox in GridView (at least one checked) using JavaScript in ASP.Net


Hi all,

try this example to Validate CheckBox in GridView (at least one checked) using JavaScript in ASP.Net

– HTML Markup :

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Text='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select at least one record."
ClientValidationFunction="Validate" ForeColor="Red"></asp:CustomValidator>


<asp:Button ID="Button1" runat="server" Text="Submit" />

– Binding the GridView control in Code behind :

protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "Mark John", "United States");
dt.Rows.Add(2, "Yasser Zaid", "Egypt");
dt.Rows.Add(3, "Ahmed Ali", "Saudi Arabia");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}

– CustomValidator JavaScript Validation function :

<script type="text/javascript">
function Validate(sender, args) {
var gridView = document.getElementById("<%=GridView1.ClientID %>");
var checkBoxes = gridView.getElementsByTagName("input");
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].type == "checkbox" && checkBoxes[i].checked) {
args.IsValid = true;
return;
}
}
args.IsValid = false;
}
</script>

Hope this helps

Good Luck.

Advertisements
Categories: ASP.Net, Javascript
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: