Adding a checkbox column to asp.net gridview - c#

I have a couple questions when it pertains to adding a CheckBox column to gridview in asp.net and getting multiple values. First off I see everyone adding OnCheckedChanged="chkview_CheckedChanged" to their aspx page but when you click on the CheckBox to set its actions it does not open OnCheckedChanged="chkview_CheckedChanged". It opens SelectedIndexChanged event instead. What I am trying to do is when they select a CheckBox it adds the corresponding rows info to the TextBox. Here is what I am currently using to set the values. How can I use a selected CheckBox instead?
protected void dropGridView_SelectedIndexChanged1(object sender, EventArgs e)
{
GridViewRow row = dropdeadGridView.SelectedRow;
IDTextBox.Text = row.Cells[1].Text;
loadnumTextBox.Text = row.Cells[2].Text;
}
Once done with that how can you make it to where it will get every row that is checked instead of just one which is what is my current problem. I am looking for a way to select multiple rows and have a select button. I have done a lot of looking and can find nothing on it so I am trying to accomplish this with CheckBoxes instead. Any ideas how I can add this and get the multiple rows that can be selected. Thank you in advance.
Here is my edit* Posting asp code for CheckBox column:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="SelectCheckBox" runat="server" OnCheckedChanged="SelectCheckBox_OnCheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>

First you have to set autopostback attribute to true :
<asp:CheckBox ID="SelectCheckBox" runat="server" AutoPostBack="true"
OnCheckedChanged="SelectCheckBox_OnCheckedChanged"/>
In your case, SelectedIndexChanged is sent by the gridview. For the checkbox event you have to use OnCheckedChanged event :
protected void SelectCheckBox_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chk = sender as CheckBox ;
if(chk.Checked)
{
GridViewRow row = (GridViewRow)chk.NamingContainer;
IDTextBox.Text = row.Cells[1].Text;
loadnumTextBox.Text = row.Cells[2].Text;
}
}
If you want to loop through all selected checkboxes :
var rows = dropdeadGridView.Rows;
int count = dropdeadGridView.Rows.Count;
for (int i = 0; i < count; i++)
{
bool isChecked = ((CheckBox)rows[i].FindControl("chkBox")).Checked;
if(isChecked)
{
//Do what you want
}
}

HTML Gridview example
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Class="table table-striped table-bordered" ShowHeaderWhenEmpty="true" HeaderStyle-HorizontalAlign="Center" RowStyle-HorizontalAlign="Center" HorizontalAlign="Center" Height="40px" Width="80%" EmptyDataText="No Stock in The Shop"> <Columns> <asp:TemplateField> <HeaderTemplate> <asp:CheckBox ID="chkAllSelect" runat="server" onclick="checkAll(this);" /> </HeaderTemplate> <ItemTemplate> <asp:CheckBox ID="chkSelect" onclick="Check_Click(this);EnableBTN(this);" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="SHOP_CODE" HeaderText="SHOP CODE" /> <asp:BoundField DataField="ITEM_CODE" HeaderText="ITEM CODE" /> <asp:BoundField DataField="ITEM_NAME" HeaderText="ITEM NAME" /> <asp:BoundField DataField="COLOR_CODE" HeaderText="COLOR CODE" /> <asp:BoundField DataField="COLOR_NAME" HeaderText="COLOR NAME" /> <asp:BoundField DataField="STOCK_NO" HeaderText="STOCK NUMBER" /> <asp:BoundField DataField="STOCK_IN_HAND" HeaderText="STOCK IN HAND" /> <asp:BoundField DataField="LOCATION_CD" HeaderText="LOCATION" /> <asp:TemplateField HeaderText="NO OF QUANTITY"> <ItemTemplate> <asp:TextBox CssClass="form-control" onkeyup="this.value=this.value.replace(/[^0-9]/g,'');" Placeholder="Enter The Correct Qty" ID="ADJqty" runat="server" AutoCompleteType="Disabled" Text=""></asp:TextBox> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
Use this function check all the gridview check box
function checkAll(objRef) {
var GridView = objRef.parentNode.parentNode.parentNode;
var inputList = GridView.getElementsByTagName("input");
for (var i = 0; i < inputList.length; i++) {
//Get the Cell To find out ColumnIndex
var row = inputList[i].parentNode.parentNode;
if (inputList[i].type == "checkbox" && objRef != inputList[i]) {
if (objRef.checked) {
//If the header checkbox is checked
//check all checkboxes
//and highlight all rows
row.style.backgroundColor = "#e3f1ff";
inputList[i].checked = true;
$('#DummyBTNAUTHLeave').prop('disabled', false);
$('#DummyBTNRJTLeave').prop('disabled', false);
}
else {
//If the header checkbox is checked
//uncheck all checkboxes
//and change rowcolor back to original
if (row.rowIndex % 2 == 0) {
//Alternating Row Color
row.style.backgroundColor = "rgba(0,0,0,.05)";
}
else {
row.style.backgroundColor = "white";
}
inputList[i].checked = false;
$('#DummyBTNAUTHLeave').prop('disabled', true);
$('#DummyBTNRJTLeave').prop('disabled', true);
}
}
}
}
check the specifyed checkbox in gridview
function Check_Click(objRef) {
//Get the Row based on checkbox
var row = objRef.parentNode.parentNode;
if (objRef.checked) {
//If checked change color to Aqua
row.style.backgroundColor = "#e3f1ff";
}
else {
//If not checked change back to original color
if (row.rowIndex % 2 == 0) {
//Alternating Row Color
row.style.backgroundColor = "rgba(0,0,0,.05)";
}
else {
row.style.backgroundColor = "white";
}
}
//Get the reference of GridView
var GridView = row.parentNode;
//Get all input elements in Gridview
var inputList = GridView.getElementsByTagName("input");
for (var i = 0; i < inputList.length; i++) {
//The First element is the Header Checkbox
var headerCheckBox = inputList[0];
//Based on all or none checkboxes
//are checked check/uncheck Header Checkbox
var checked = true;
if (inputList[i].type == "checkbox" && inputList[i] != headerCheckBox) {
if (!inputList[i].checked) {
checked = false;
break;
}
}
}
headerCheckBox.checked = checked;
}

Related

How to loop through each and every row, put value in gridview column cells

i have gridview with 3 columns and 100 rows. and one submit button out of gridview.
here first 2 column is bounded field and 3rd one is Label (templatefield) .
Now, I want to change status of 3rd column and display it to gridview when loop run.
i want to
when i=0 then i want to change label's value to "SUCESS" and display on Gridview,
i=1 then i want to change label's value to "SUCESS" and display on Gridview,
and so on till i=100.
Gridview
<asp:GridView ID="GvCategoryLive" runat="server" AutoGenerateColumns="False" EmptyDataText="No Records Found !" >
<Columns>
<asp:BoundField DataField="UnitName" HeaderText="Unit Name" />
<asp:BoundField DataField="CreateDate" HeaderText="Created Date" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="UnitMesurement_Id" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am trying something like this
protected void btnSave_Click(object sender, EventArgs e)
{
if (btnSave.Text == "Save")
{
for (int i = 0; i < GvCategoryLive.Rows.Count; i++)
{
System.Threading.Thread.Sleep(9000);
GvCategoryLive.Rows[i].Cells[2].Text = "Success";
}
}
}
I really dont remember the gridviews and asp.net webforms but
You may use setTimeout in javascript
var rowCount = 100;// get row count here
for(int i = 0; i < rowCount ; i++)
{
setTimeout($('#cell'+i).html('Success'), 9000);
}
You could try like this:
protected void btnSave_Click(object sender, EventArgs e)
{
if (btnSave.Text == "Save")
{
foreach(GridViewRow row in GvCategoryLive.Rows) {
if(row.RowType == DataControlRowType.DataRow) {
Label UnitMesurement_Id= row.FindControl("UnitMesurement_Id") as Label ;
UnitMesurement_Id.Text = "Success";
}
}
}
}
Because you are not setting the value of a cell but label inside that cell, you should change this-
GvCategoryLive.Rows[i].Cells[2].Text = "Success";
into-
Label UnitMesurement_Id = GvCategoryLive.Rows[i].FindControl("UnitMesurement_Id") as Label;
UnitMesurement_Id.Text = "Success";

Get data from dynamically created controls in TemplateFields for gridview

I have a webpage that has a gridview which is bound to a list of custom objects but also has 1 dynamically created TemplateFields. These fields are created at Page_PreRender and can be a textbox or dropdownlist based on the object in the list. I have a button at the bottom of the page that needs to save all the data inputed in the dynamic objects when pressed. When i try to find the dynamic control i am unable to do so using the FindControl() method. It always comes back blank.
How can i retrieve the user entered/selected data?
This is my gridview
<div id="divSearchCriteriaGrid" runat="server" class="padding-top-15">
<asp:GridView ID="gvSearchCriteria" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvSearchCriteria_OnRowDataBound" GridLines="None">
<Columns>
<asp:BoundField DataField="SearchFieldId" Visible="False" />
<asp:TemplateField HeaderText="Search Field">
<ItemTemplate>
<asp:CheckBox ID="cbDisplay" runat="server" AutoPostBack="False" onclick="ToggleCriteriaControls(this)" />
</ItemTemplate>
<ItemStyle Width="25%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Begin Criteria">
<ItemStyle Width="35%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="End Criteria">
<ItemStyle Width="35%" />
</asp:TemplateField>
<asp:BoundField DataField="ControlTypeId" Visible="False" />
</Columns>
</asp:GridView>
</div>
And this is my code behind for creating the controls:
public void Page_PreRender(object sender, EventArgs e)
{
TryAction(PrepareLoad);
}
private void PrepareLoad()
{
if (IsPostBack) return;
BindData();
}
private void BindData()
{
gvSearchCriteria.DataSource = null;
gvSearchCriteria.DataSource = SearchFieldList;
gvSearchCriteria.DataBind();
}
protected void gvSearchCriteria_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
SearchField searchField = e.Row.DataItem as SearchField;
if (searchField != null)
{
e.Row.Cells[0].Text = searchField.SearchFieldId.ToString();
e.Row.Cells[4].Text = searchField.ControlTypeId.ToString();
CheckBox checkBox = (CheckBox)e.Row.FindControl("cbDisplay");
checkBox.Text = searchField.FieldDescription;
checkBox.Checked = searchField.Checked;
checkBox.Enabled = true;
if (searchField.ControlTypeId.ToString() == "1")
{
RadTextBox textBox = new RadTextBox();
textBox.ID = "txtBoxBegin";
e.Row.Cells[2].Controls.Add(textBox);
textBox = new RadTextBox();
textBox.ID = string.Format("txt{0}End", searchField.SearchFieldId);
e.Row.Cells[3].Controls.Add(textBox);
}
else if (searchField.ControlTypeId.ToString() == "2")
{
RadComboBox comboBox = new RadComboBox();
comboBox = new SearchService().GetRadComboBoxById(searchField.SearchFieldId);
comboBox.ID = string.Format("cbo{0}Begin", searchField.SearchFieldId);
e.Row.Cells[2].Controls.Add(comboBox);
}
}
}
}
This all works good and the controls get created with the checkbox.
Here is my code for trying to loop through each row of the gridview to get the user entered data which does not work.
private void Save()
{
foreach (GridViewRow row in gvSearchCriteria.Rows)
{
CheckBox include = (CheckBox)row.FindControl("cbDisplay");
int id, controlTypeId;
string criteriaOne = string.Empty;
string criteriaTwo = string.Empty;
if (!include.Checked) continue;
id = int.Parse(row.Cells[0].Text);
if (controlTypeId == "1")
{
RadTextBox radTextBox = (RadTextBox) row.FindControl("txtBoxBegin");
if (radTextBox != null)
{
criteriaOne = radTextBox.Text;
}
radTextBox = (RadTextBox)row.FindControl("txtBoxEnd");
if (radTextBox != null)
{
criteriaTwo = radTextBox.Text;
}
}
else if(controlTypeId == "2")
{
RadComboBox radComboBox = (RadComboBox)row.FindControl(string.Format("cbo{0}Begin",id));
if (radComboBox != null)
{
criteriaOne = radComboBox.SelectedValue;
}
}
}
}
The radTextBox and radComboBox variables i am trying to get using the FindControlId always comes back null.
cell 0 comes back ok each time with the correct Id. the cbDisplay checkbox always returns whether the row is checked or not and cell 4 gets the ControlTypeId just fine. It is the TemplateFields that i cannot get the values for.
Any help is greatly appreciated.
I was able to get the information from the dynamic controls once i moved the BindData() function to the Page_Init instead of the Page_PreRender().

How to Uncheck Select All Checkbox when one checkbox is Unchecked

I have a checkbox named Select All. When I click this then all other check box inside my Gridview is Checked. But I want when anyone of the checkbox inside the grid will be unchecked then this Select All Checkbox will automatically uncheck. Is there anyone who can help me on this Please?
Thank you.
function SelectheaderCheckboxes(headerchk) {
debugger
var gvcheck = document.getElementById('gvdetails');
var i;
//Condition to check header checkbox selected or not if that is true checked all checkboxes
if (headerchk.checked) {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = true;
}
}
//if condition fails uncheck all checkboxes in gridview
else {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = false;
}
}
}
<asp:GridView ID="gvdetails" runat="server" DataSourceID="dsdetails" onrowdatabound="gvdetails_RowDataBound" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkheader" runat="server" onclick="javascript:SelectheaderCheckboxes(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkchild" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can do this on the client or the server side
Client side using javascript/jquery
As the checkboxes are added dynamically you will need to use the on method to bind the checkboxes to the function and fire it when their state changes.
$(document).ready(function() {
$(".checkbox").on("change", function() {
if(!$(this).is(":checked")){
$(".selectAll").prop('checked', false);
}
});
});
Here is a jsFiddle with a full functioning select All that will:
Select All / Deselect All
Untick Select All when one of the checkboxes is unticked
Tick select All when all checkboxes are ticked
Server side
use an event handler to on a postback(ajax) when a checkbox is unticked and loop through all checkboxes and untick them
Font-end uses ajax to do a partial postback to update the gridview.
the select all checkbox and gridview checkboxes will trigger the postback.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="gvCheckBoxes" runat="server">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="cbCheckBox" OnCheckedChanged="CheckBoxChanged" AutoPostBack="true" runat="server" />
</ItemTemplate>
/asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="cbSelectAll"/>
</Triggers>
</asp:UpdatePanel>
Code Behind
The select All check box event handler loops through the gridview and finds the checkboxes.
It ticks them if the select all checkbox is ticked otherwise it unticks them
The gridview checkbox event handler loops through the checkboxes and sets a flag to determine if it should tick or untick the select all checkbox. It exists the loop if any of the checkboxes are not ticked as select all must therefore be unticked as well
public void SelectAll (Object sender, Eventargs e)
{
foreach (var row in grid.Rows)
{
var checkBox = (CheckBox)row.FindControl("cbCheckBox");
checkBox.Checked = cbSelectAll.Checked;
}
}
public void CheckBoxChanged(Object sender, Eventargs e)
{
var isSelectAll = true;
foreach (var row in grid.Rows)
{
var checkBox = (CheckBox)row.FindControl("cbCheckBox");
if(!checkBox.Checked)
{
isSelectAll = false;
break;
}
}
cbSelectAll.Checked = isSelectAll;
}
Best way I can think of is to convert the GridView's CheckBoxField to a TemplateField. Then wire up the new asp:CheckBox in your TemplateField to the CheckedChanged event. In your code-behind, you handle the CheckedChanged event, then when any of the checkboxes change to unchecked, you can toggle your "check all" checkbox.
Look at this code. hope this will help you
<div>
<asp:CheckBox ID="chkSelectAll" runat="server" />
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" oncheckedchanged="chkSelect_CheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
bool isFound = false;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
if (chkSelect.Checked == false)
{
isFound = true;
break;
}
}
if (isFound)
{
chkSelectAll.Checked = false;
}
else
{
chkSelectAll.Checked = true;
}
}
The following code should work. I tested it.
Javascript:
<script type="text/javascript">
function OnOneCheckboxSelected(chkB) {
var IsChecked = chkB.checked;
var Parent = document.getElementById('gridFileList');
var cbxAll;
var items = Parent.getElementsByTagName('input');
var bAllChecked = true;
for (i = 0; i < items.length; i++) {
if(items[i].id.indexOf('cbxSelectAll') != -1){
cbxAll = items[i];
continue;
}
if (items[i].type == "checkbox" && items[i].checked == false) {
bAllChecked = false;
break;
}
}
cbxAll.checked = bAllChecked;
}
function SelectAllCheckboxes(spanChk) {
var IsChecked = spanChk.checked;
var cbxAll = spanChk;
var Parent = document.getElementById('gridFileList');
var items = Parent.getElementsByTagName('input');
for (i = 0; i < items.length; i++) {
if (items[i].id != cbxAll.id && items[i].type == "checkbox") {
items[i].checked = IsChecked;
}
}
}
</script>
ASPX Markup:
<asp:TemplateField HeaderText="Select">
<HeaderTemplate>
<asp:CheckBox ID="cbxSelectAll" OnClick="javascript:SelectAllCheckboxes(this);" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox OnClick="javascript:OnOneCheckboxSelected(this);" ID="cbxSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Above code I modifiyed it, if user unchecked the child rows of grid. grid header will automatically uncheck.
<script type="text/javascript">
function UncheckHeader(headerchk) {
var gvcheck = document.getElementById('gvdetails');
var inputs = gvcheck.rows[0].getElementsByTagName('input');
inputs[0].checked = false;
}
function SelectAll(headerchk) {
var gvcheck = document.getElementById('gvdetails');
var i;
// if true checked all checkboxes
if (headerchk.checked) {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = true;
}
}
//if condition fails uncheck all checkboxes in gridview
else {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = false;
}
}
}
</script>
<asp:GridView ID="gvdetails" runat="server" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkheader" runat="server" onclick="javascript:SelectAll(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkchild" runat="server" onclick="javascript:UncheckHeader(this)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
more details here

how to prevent disabled checkboxes of gridview from getting checked when select all checkbox is clicked?

I have used gridview in my aspx page.. In that i have a check box at each row including header..
By clicking the header checkbox it will check all the checkboxes including disabled checkboxes in gridview.. I need to avoid the disabled checkbox from getting checked
This is my gridview code:
<asp:GridView ID="CrowdRatingGrid" runat="server" AutoGenerateColumns="false" AllowPaging="true" PageSize="4" OnPageIndexChanging="CrowdRatingGrid_PageIndexChanging" ViewStateMode="Enabled">
<PagerSettings Mode="Numeric" PageButtonCount="4" />
<Columns>
<asp:TemplateField HeaderStyle-BackColor="#DBE2E2" HeaderStyle-Width="60px" HeaderStyle-HorizontalAlign="Center"
HeaderStyle-Height="62px">
<HeaderTemplate>
<asp:CheckBox ID="SelectAll" runat="server" onclick="SelectAll(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="CheckRow" CssClass="SelectRow" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is my js code for selecting all checkbox:
function SelectAll(objRef) {
var GridView = objRef.parentNode.parentNode.parentNode;
var inputList = GridView.getElementsByTagName("input");
for (var i = 0; i < inputList.length; i++) {
var row = inputList[i].parentNode.parentNode;
if (inputList[i].type == "checkbox" && objRef != inputList[i]) {
if (objRef.checked) {
inputList[i].checked = true;
}
else {
inputList[i].checked = false;
}
}
}
}
Please help in achieving this? What change should i make in js to achieve my requirement?
Change condition to
if (objRef.checked && !inputList[i].disabled) {
inputList[i].checked = true;
}
else {
inputList[i].checked = false;
}

how to check status of checkboxes in gridview columns on click of button

T have used checkbox column in gridview. On click of a linkbutton, it should be checked that checkboxes in gridview are checked or not. If none check box is checked then it should display alert("Check at leat one check box").
You will have to add some custom Javascript to your page for the client-side alert to show. Here's a method that I've written that works with a GridView called 'GridView1' (this should be the default name if you've just dragged the control onto your ASPX page):
<script type="text/javascript">
function ClientCheck() {
var valid = false;
var gv = document.getElementById("GridView1");
for (var i = 0; i < gv.all.length; i++) {
var node = gv.all[i];
if (node != null && node.type == "checkbox" && node.checked) {
valid = true;
break;
}
}
if (!valid) {
alert("Invalid. Please select a checkbox to continue.");
}
return valid;
}
</script>
You can see that it sets a variable to the GridView control to start with, then iterates through all the children in a for loop. If the child is a checkbox and it is checked, then we set the valid variable to true. If we get to the end of the iteration and no checked checkboxes are found, then valid remains false and we execute the alert.
To link this into your GridView on your ASPX page, first make the button column a TemplateField and surround the LinkButton with your client-side code. If you've used the designer to set up your columns, you can use the "Convert this field into a TemplateField" link in the column editor). Here's an example of the source you'll end up with:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1">
<Columns>
<asp:TemplateField HeaderText="Button Field" ShowHeader="False">
<ItemTemplate>
<span onclick="return ClientCheck();">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="IDClick" Text='<%# Eval("YourDataSourceItem") %>'></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
// ...your remaining columns...
Using the TemplateField lets us add any client-side code we like. Here we're adding a span and using onclick to call our ClientCheck method.
If you aren't bothered about the alert, you could achieve your aims by using a CustomValidator control, which executes on the server-side.
I hope this helps.
I found the answer. and its working...
function checkBoxselectedornot()
{
var frm=document.forms['aspnetForm'];
var flag=false;
for(var i=0;i<document.forms[0].length;i++)
{
if(document.forms[0].elements[i].id.indexOf('chkDownloadSelectedEvent')!=-1)
{
if(document.forms[0].elements[i].checked)
{
flag=true
}
}
}
if (flag==true)
{
return true
}else
{
alert('Please select at least one Event.')
return false
}
}
and girdview code is...
<asp:BoundField ItemStyle-Width ="100px" DataField ="EventStartDate" DataFormatString ="{0:g}" HeaderText ="<%$ Resources:stringsRes, ctl_EventList_StartDate %>" SortExpression ="EventStartDate" HtmlEncode ="true" ItemStyle-Wrap ="false" />
<asp:BoundField ItemStyle-Width="100px" DataField="EventDate" DataFormatString="{0:g}" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Date %>" SortExpression="EventDate" HtmlEncode="true" ItemStyle-Wrap="false" />
<asp:ButtonField ItemStyle-Width="150px" ButtonType="Link" DataTextField="EventName" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Event %>" SortExpression="EventName" CommandName="show_details" CausesValidation="false" />
<asp:BoundField DataField="EventLocation" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Location %>" SortExpression="EventLocation" />
<asp:TemplateField HeaderText ="Select">
<ItemTemplate >
<asp:CheckBox ID="chkDownloadSelectedEvent" runat ="server" AutoPostBack ="false" Onclick="eachCheck();"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle Height="25px" />
<HeaderStyle Height="30px"/>
</asp:GridView>
and there is a link button ....
I havnt used the checkbox in grid view but would you not do a for loop around the columns in gridview and check the state? Myabe add a count and if 0 then alert.
var grid = document.getElementById("gridId"); //Retrieve the grid
var inputs = grid.getElementsByTagName("input"); //Retrieve all the input elements from the grid
var isValid = false;
for (var i=0; i < inputs.length; i += 1) { //Iterate over every input element retrieved
if (inputs[i].type === "checkbox") { //If the current element's type is checkbox, then it is wat we need
if(inputs[i].checked === true) { //If the current checkbox is true, then atleast one checkbox is ticked, so break the loop
isValid = true;
break;
}
}
}
if(!isValid) {
alert('Check at least one checkbox');
}

Categories