Click here to Skip to main content
12,451,227 members (54,081 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# .NET
Hi Everyone....

How to check and uncheck Checkboxcolumns in datagridview by an another checkbox which is outside of that datagridview .

i have to fulfill three criteria which are explain below
1.If outside checkbox is checked then all datagridview checkboxes are checked and viceversa .

2.If all datagridview checkboxes are checked then outside checkbox will be also checked .

and
3. After clicking of outside checkbox all checkboxes are checked but if one of them is unchecked then ohers remain same but outside checkbox will be unchecked .

How can i do that ?

for first condition i have done these..

if (checkBox1.Checked == true)
 {
   for (int i = 0; i < datagridview1.RowCount; i++)
      {
        datagridview1[0, i].Value = true;
       }
  }
but for second ad third condition i can not get proper or exact solution....
please help..

Thank You
Posted 23-Sep-12 21:17pm
Updated 23-Sep-12 21:21pm
D-Kishore4.2K
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

--> note: wpf and c#
----------------------

for your first criteria (1.If outside checkbox is checked then all datagridview checkboxes are checked and viceversa)
bind a short clr property

/// <summary>
        ///for checkbox "select all"
        /// </summary>
        private short isAllSelected;
        public short IsAllSelected
        {
            get
            {
                return isAllSelected;
            }
            set
            {
                isAllSelected = value;
                OnPropertyChanged("IsAllSelected");
 
                //for checking and unchecking based on select all checked
                SelectAllDesignation();
            }
        }

datagridview databinding create a property
/// <summary>
        /// for designation
        /// </summary>
        private DataTable dtDesignation;
        public DataTable Designation
        {
            get
            {
                return dtDesignation;
            }
            set
            {
                dtDesignation = value;
                OnPropertyChanged("Designation");               
            }
        }

and add a column named as IsSelected

DataColumn dtCol = new DataColumn("IsSelected", typeof(Int16));
                dtCol.DefaultValue = 0;
                Designation = objHRmain.FetchDesignation(dtConditions); //fetch your data
                Designation.Columns.Add(dtCol);
                Designation.AcceptChanges();



/// <summary>
        /// for select all
        /// </summary>
        private void SelectAllDesignation()
        {
            if (Designation != null && Designation.Rows.Count > 0)
            {
                if (IsAllSelected == 1)
                {
                    foreach (DataRow dr in Designation.Rows)
                    {
                        dr["IsSelected"] = true;
                    }
                }
                else
                {
                    foreach (DataRow dr in Designation.Rows)
                    {
                        dr["IsSelected"] = false;
                    }
                }
            }
        }


for your 2nd and 3rd criteria(2.If all datagridview checkboxes are checked then outside checkbox will be also checked .and
3. After clicking of outside checkbox all checkboxes are checked but if one of them is unchecked then ohers remain same but outside checkbox will be unchecked )

create a event handler (like command ,checked etc.. )
on that event write this code
here am used command binding

private void SelectDetails_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Parameter != null)
            {
                DataRowView drvSelected = e.Parameter as DataRowView;
                if (Convert.ToInt16(drvSelected.Row["IsSelected"]) == 0)
                {
                    isAllSelected = 0;
                    OnPropertyChanged("IsAllSelected");
                }
                else
                {
                    if (Designation.AsEnumerable().Count(dr => Convert.ToInt16(dr["IsSelected"]) == 1) == Designation.Rows.Count)
                    {
                        isAllSelected = 1;
                        OnPropertyChanged("IsAllSelected");
                    }
                    else
                    {
                        isAllSelected = 0;
                        OnPropertyChanged("IsAllSelected");
                    }
                }
            }
        }


and also dont forget to implement inheritance INotifyPropertyChanged and its implementation

#region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler == null) return;
            handler(this, new PropertyChangedEventArgs(name));
        }
        #endregion
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

<script type="text/javascript">
    $(document).ready(function () {
 
        //For outside checkbox to check/uncheck grid checkbox columns
        $("[id*='chkSelectAll']").change(function () {
            var IsChecked = false;
            if ($(this).is(":checked")) {
                IsChecked = true;
            }
            $("[id*='grdCheckBoxDemo'] tr").each(function () {
                $(this).find("[id*='chkCheckBoxCol']").attr("checked", IsChecked);
            });
        });
 
        //For checkbox column checkbox to check/uncheck outside checkbox
        $("[id*='chkCheckBoxCol']").change(function () {
            var counter = 0;
            $("[id*='grdCheckBoxDemo'] tr").each(function () {
                if ($(this).find("[id*='chkCheckBoxCol']").is(":checked")) {
                    counter++;
                }
            });
            //check total checked rows if it matches with gridview row then checked outside
            //check box else uncheck it
            //here i have remove one row from total row of gridview because it will cout
            //header row also so we need to take care for that also
            if (($("[id*='grdCheckBoxDemo'] tr").length - 1) == counter) {
                $("[id*='chkSelectAll']").attr("checked", true);
            }
            else {
                $("[id*='chkSelectAll']").attr("checked", false);
            }
        });
    });
</script>

instead of using code behind method you simply use jquery to check or uncheck all the check boxes in gridview using outside check box. it's improve performance because it not cause post back trip to server.

here in the above function chkSelectAll is id of out side check box
and grdCheckBoxDemo is id of gridview containing check box columns
and chkCheckBoxCol is id of check box which is inside check box column. replace this ids with your actual ids and make some modification as per your required logic if needed.

i hope this is working fine for your solutions.
  Permalink  
v3
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Check/Uncheck all the Checkboxes in Gridview</title>
<script type="text/javascript">
// Select/Deselect checkboxes based on header checkbox
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;
}
}
}
//function to check header checkbox based on child checkboxes condition
function Selectchildcheckboxes(header) {
var ck = header;
var count = 0;
var gvcheck = document.getElementById('gvdetails');
var headerchk = document.getElementById(header);
var rowcount = gvcheck.rows.length;
//By using this for loop we will count how many checkboxes has checked
for (i = 1; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
if (inputs[0].checked) {
count++;
}
}
//Condition to check all the checkboxes selected or not
if (count == rowcount-1) {
headerchk.checked = true;
}
else {
headerchk.checked = false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<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>
<asp:SqlDataSource ID="dsdetails" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection %>"
SelectCommand="select * from UserInfo" >
</asp:SqlDataSource>
</div>
</form>
</body>
</html>


protected void gvdetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox headerchk = (CheckBox)gvdetails.HeaderRow.FindControl("chkheader");
CheckBox childchk = (CheckBox)e.Row.FindControl("chkchild");
childchk.Attributes.Add("onclick", "javascript:Selectchildcheckboxes('" + headerchk.ClientID + "')");
}
}

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=Strange_Pirate;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >


<img src="http://imgboot.com/images/sureshdasari/selectdeselectcheckboxes.gif" alt="Demo" />


Check the complete solution.

Thank To SureshDasari Smile | :)
  Permalink  
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160826.1 | Last Updated 27 Sep 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100