选中/取消选中动态创建的gridview的所有复选框 [英] Check/ uncheck all the checkboxs of dynamically created gridview

查看:56
本文介绍了选中/取消选中动态创建的gridview的所有复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的aspx页面中有两个DropDownLists和一个Gridview控件。 gridview的所有列都是根据用户从下拉列表中的选择动态生成的。



Gridview包含2个包含复选框的BoundField和N个模板字段。 BoundFields是常量,模板化字段的数量根据下拉列表选择而变化。复选框是使用Itemplate创建的。



现在,当选中Gridview标题中的复选框时,我需要选中取消选中gridview列的所有复选框。



我向Itemplate添加了一个CheckedChanged事件,它也没有调用该方法。请帮我。这是我的代码:

Default.aspx-



I have two DropDownLists and a Gridview control in my aspx page. All the columns of gridview are dynamically generated according to user selection from Dropdownlists.

The Gridview Contains 2 BoundField and N templated fields Containing Checkboxes. The BoundFields are constant and the number of templated fields vary according to dropdownlist selection. The Checkboxes are created using Itemplate.

Now I need to Check Uncheck all checkboxs of a gridview column when Checkbox in the Gridview Header is checked.

I added a CheckedChanged event to Itemplate it is not calling that method also. Please help me. Here is my Code:
Default.aspx-

<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="smgr" runat="server">
    </asp:ScriptManager>
    <div class="col-md-12 panel-info">
        <div class="content-box-header panel-heading">
            Employee Salary Structure
        </div>
        <div class="content-box-large">
            <div class="row">
                <div class="col-sm-3">
                    <b>Company:</b>&emsp;
                    <asp:DropDownList ID="ddlcompany" runat="server" Height="20px" Width="70%">
                        <asp:ListItem Text="All">All</asp:ListItem>
                    </asp:DropDownList>
                </div>
                <div class="col-sm-4">
                    <b>Allowance Group:</b>&emsp;
                    <asp:DropDownList ID="ddlallowancegroup" runat="server" Height="20px" 

                        Width="60%" onselectedindexchanged="ddlallowancegroup_SelectedIndexChanged">
                        <asp:ListItem Text="All">All</asp:ListItem>
                    </asp:DropDownList>
                </div>
                <asp:ImageButton ID="btnsearch" runat="server" ImageUrl="~/Admincontrol/Images/Search.png"

                    OnClick="btnsearch_Click" />
                <asp:ImageButton ID="btnclear" runat="server" ImageUrl="~/Admincontrol/Images/Clear.png" />
            </div>
            <hr style="border: 1px solid #c9c9c9" />
<div class="row">
                <div class="col-sm-10">
                            <asp:Label ID="hndId" Visible="false" runat="server"></asp:Label>
                            <asp:GridView ID="gvEmpSalaryStructure" Width="100%" CssClass="grdview" runat="server"

                                BorderColor="White" GridLines="Both" ForeColor="#333333"

                                CellSpacing="1" CellPadding="3" AllowSorting="true" AutoGenerateColumns="False"

                                OnRowCommand="gvEmpSalaryStructure_RowCommand">

                                <FooterStyle BackColor="#507CD1" ForeColor="White" Font-Bold="True"></FooterStyle>
                                <Columns>
                                </Columns>
                                <RowStyle BackColor="#EFF3FB" />
                                <EmptyDataTemplate>
                                    <div style="text-align: left; border: 0px">
                                        <strong>No Data Available...</strong>
                                    </div>
                                </EmptyDataTemplate>
                                <EditRowStyle BackColor="Black" />
                                <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="False" ForeColor="#333333" />
                                <PagerStyle BackColor="White" ForeColor="#2461BF" HorizontalAlign="Right" />
                                <HeaderStyle BackColor="#CCDDEF" Font-Bold="False" ForeColor="Black" VerticalAlign="Middle"  HorizontalAlign="Center"/>
                                <AlternatingRowStyle BackColor="White" CssClass="odd" />
                                <PagerSettings FirstPageText="First" 

                                    LastPageText="Last" Mode="NumericFirstLast"

                                    NextPageText="Next" PreviousPageText="Prev" />
                            </asp:GridView>
                        </div>







Default.aspx.cd(Code-Behind):

Method for getting No. of Checkbox columns by Dropdownlist selection-

private DataTable GetAllowanceGroup()
        {
            string hndID = ddlallowancegroup.SelectedValue;
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            if (ddlallowancegroup.SelectedValue == "All")
            {
                ds = employee.GetDistinctvalues("AllowanceName", "tbl_Pay_Allowances");
                dt = ds.Tables[0];
                return dt;
            }
            else
            {
                ds = allowances.getDistinctAllowanceName(Convert.ToInt32(hndID));
                dt = ds.Tables[0];
                return dt;
            }
        }
Creating Gridview Template-

private void CreateGridColumns()
        {
            gvEmpSalaryStructure.Columns.Clear();

            BoundField empid = new BoundField();
            empid.HeaderText = "Emp ID";
            empid.DataField = "EmpID";
            empid.Visible = false;
            empid.ItemStyle.Width = Unit.Percentage(30);
            gvEmpSalaryStructure.Columns.Add(empid);

            BoundField empname = new BoundField();
            empname.HeaderText = "Emp Name";
            empname.DataField = "EmpName";
            empname.ItemStyle.Width = Unit.Percentage(30);
            empname.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
            gvEmpSalaryStructure.Columns.Add(empname);

            var tblAllowanceGroup = GetAllowanceGroup();
            foreach (DataRow row in tblAllowanceGroup.Rows)
            {
                String AllowanceGroupName = row.Field<String>("AllowanceName");
                TemplateField field = new TemplateField();
                //Initalize the DataField value.
                field.ItemTemplate = new GridViewCheckBoxTemplate(DataControlRowType.DataRow, AllowanceGroupName, AllowanceGroupName, "CheckBox");
                field.HeaderTemplate = new GridViewCheckBoxTemplate(DataControlRowType.Header, AllowanceGroupName, AllowanceGroupName, "CheckBox");
                field.ItemStyle.Width = 70;
                field.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                gvEmpSalaryStructure.Columns.Add(field);
            }
Itemplate() Method-

public class GridViewCheckBoxTemplate : ITemplate
             {
                 private DataControlRowType templateType;
                 private string columnName;
                 private string columnNameBinding;
                 private string controlType;


                 public GridViewCheckBoxTemplate(DataControlRowType type, string colname, string colNameBinding, string ctlType)
                 {
                     templateType = type;
                     columnName = colname;
                     columnNameBinding = colNameBinding;
                     controlType = ctlType;
                 }

                 public void InstantiateIn(System.Web.UI.Control container)
                 {
                     switch (templateType)
                     {
                         case DataControlRowType.Header:
                            if(controlType == "CheckBox")
                            {
                                var chb1 = new CheckBox();
                                chb1.Text = columnName + "&emsp;";
                                chb1.ID = columnName;
                                chb1.TextAlign = TextAlign.Left;
                                chb1.CheckedChanged+= new EventHandler(this.chb1_CheckedChanged);
                                chb1.LabelAttributes.CssStyle.Add("align", "center");
                                container.Controls.Add(chb1);
                            }
                            else
                            {
                             Literal lc = new Literal();
                             lc.Text = columnName;
                             container.Controls.Add(lc);
                             }
                             break;
                         case DataControlRowType.DataRow:
                             if (controlType == "Label")
                             {
                                 Label lb = new Label();
                                 lb.ID = "lb1";
                                 lb.DataBinding += new EventHandler(this.ctl_OnDataBinding);
                                 container.Controls.Add(lb);
                             }
                             else if (controlType == "TextBox")
                             {
                                 TextBox tb = new TextBox();
                                 tb.ID = "tb1";
                                 tb.DataBinding += new EventHandler(this.ctl_OnDataBinding);
                                 container.Controls.Add(tb);
                             }
                             else if (controlType == "CheckBox")
                             {
                                 CheckBox cb1 = new CheckBox();
                                 cb1.ID = columnName;
                                 cb1.DataBinding += new EventHandler(this.ctl_OnDataBinding);
                                 container.Controls.Add(cb1);
                             }
                             else if (controlType == "HyperLink")
                             {
                                 HyperLink hl = new HyperLink();
                                 hl.ID = "hl1";
                                 hl.DataBinding += new EventHandler(this.ctl_OnDataBinding);
                                 container.Controls.Add(hl);
                             }
                            else if (controlType == "ImageButton")
                             {
                                 ImageButton ib = new ImageButton();
                                 ib.ImageUrl = "~/Admincontrol/Images/view1.gif";
                                 ib.CommandName = "Select";
                                 ib.ID = "iSelect"; 
                                 container.Controls.Add(ib);

                             }
                             break;
                         default:
                             break;
                     }
                 }

                 public void ctl_OnDataBinding(object sender, EventArgs e)
                 {
                     if (sender.GetType().Name == "Label")
                     {
                         Label lb = (Label)sender;
                         GridViewRow container = (GridViewRow)lb.NamingContainer;
                         lb.Text = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
                     }
                     else if (sender.GetType().Name == "TextBox")
                     {
                         TextBox tb = (TextBox)sender;
                         GridViewRow container = (GridViewRow)tb.NamingContainer;
                         tb.Text = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
                     }
                     else if (sender.GetType().Name == "CheckBox")
                     {
                         CheckBox cb = (CheckBox)sender;
                         GridViewRow container = (GridViewRow)cb.NamingContainer;
                         object dataValue = ((DataRowView)container.DataItem)[columnNameBinding];
                         cb.Checked = dataValue != DBNull.Value && (bool)dataValue;

                     }
                     else if (sender.GetType().Name == "HyperLink")
                     {
                         HyperLink hl = (HyperLink)sender;
                         GridViewRow container = (GridViewRow)hl.NamingContainer;
                         hl.Text = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
                         hl.NavigateUrl = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
                     }
                    else if (sender.GetType().Name == "ImageButton")
                     {
                         ImageButton ib = (ImageButton)sender;
                         GridViewRow container = (GridViewRow)ib.NamingContainer;
                         ib.ImageUrl = ((DataRowView)container.DataItem)[columnNameBinding].ToString();

                     }
                 }
                 public void chb1_CheckedChanged(object sender, EventArgs e)
                 {
                     GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
                     int index = row.RowIndex;
                     if (cb.Checked)
                     {

                     }
                 }
             }
Page_Load():

protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) {

            DataSet dscompany = new DataSet();
            ddlcompany.Items.Clear();
            ddlcompany.Items.Add("All");
            dscompany = company.GetAllCompanymaster();
            for (int i = 0; i < dscompany.Tables[0].Rows.Count; i++)
            {
                ddlcompany.Items.Add(new ListItem(dscompany.Tables[0].Rows[i]["CompanyFName"].ToString(), dscompany.Tables[0].Rows[i]["CompanyId"].ToString()));
            }
            DataSet dsallowancegroup = new DataSet();
            ddlallowancegroup.Items.Clear();
            ddlallowancegroup.Items.Add("All");
            dsallowancegroup = allowancegroup.GetAllAllowanceGroup();
            for (int i = 0; i < dsallowancegroup.Tables[0].Rows.Count; i++)
            {
                ddlallowancegroup.Items.Add(new ListItem(dsallowancegroup.Tables[0].Rows[i]["AllowanceGroupName"].ToString(), dsallowancegroup.Tables[0].Rows[i]["AllowanceGroupId"].ToString()));
            }
            GridView gvEmpSalaryStructure = new GridView();
            gvEmpSalaryStructure.DataSource = null;
            gvEmpSalaryStructure.DataBind();
            CreateGridColumns();
            BindGrid();
        }
    }
BindGrid() Method:

private void BindGrid()
        {
            var tblAllowanceGroup = GetAllowanceGroup();
            DataSet dsgrid = new DataSet();
            DataTable dtgrid = new DataTable();
            var empRow = dtgrid.NewRow();
            dtgrid.Columns.Add("EmpID");
            dtgrid.Columns.Add("EmpName");
            foreach (DataRow row in tblAllowanceGroup.Rows)
            {
                String AllowanceGroupName = row.Field<String>("AllowanceName");
                //Add column from domain-name
                dtgrid.Columns.Add(AllowanceGroupName, typeof(bool)); //CheckBox-Checked is a boolean
            }
            dtgrid.Columns.Add("");
            this.GenerateFilterExpression();
            dsgrid = employee.GetSearchEmployee(FilterExpression);
            //dsgrid = employee.GetAllEmployeeMaster();
            if (dsgrid.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i <= dsgrid.Tables[0].Rows.Count - 1; i++)
                {
                    DataRow row = dtgrid.NewRow();
                    row["EmpID"] = dsgrid.Tables[0].Rows[i]["EmployeeId"].ToString();
                    row["EmpName"] = dsgrid.Tables[0].Rows[i]["EmployeeName"].ToString();
                    foreach (DataRow row1 in tblAllowanceGroup.Rows)
                    {
                        row[row1.Field<String>("AllowanceName")] = 0;//CheckBox-Checked is a boolean
                    }
                    dtgrid.Rows.Add(row);
                }
            }
            DataView dv = dtgrid.DefaultView;
            gvEmpSalaryStructure.DataSource = dv;
            gvEmpSalaryStructure.DataBind();
            gvEmpSalaryStructure.HeaderRow.HorizontalAlign = HorizontalAlign.Center;

        }
Varying No. of Rows:

 private void GenerateFilterExpression()
    {
        if (ddlcompany.SelectedItem.Text != "All")
        {
            FilterExpression = FilterExpression + " CompanyId=" + ddlcompany.SelectedValue + " and ";
        }
        else
        {
            FilterExpression = FilterExpression + "";
        }
        if (ddlallowancegroup.SelectedItem.Text != "All")
        {
            FilterExpression = FilterExpression + " AllowanceGroupId=" + ddlallowancegroup.SelectedValue + " and ";
        }
        else
        {
            FilterExpression = FilterExpression + "";
        }
        FilterExpression = FilterExpression + "  EmployeeId > 0 and EmployeeCode != '0'";
    }





What I have tried:



I tried to add a event to Checkbox in Itemplate header. but it event is not called.



What I have tried:

I tried to add a event to Checkbox in Itemplate header. but it event is not called.

推荐答案

Please refer Gridview header checkbox select and deselect all rows using client side JavaScript and server side C# article and examples.[^]

Check Uncheck all CheckBoxes in ASP.Net GridView using jQuery[^]
Please refer Gridview header checkbox select and deselect all rows using client side JavaScript and server side C# article and examples.[^]
Check Uncheck all CheckBoxes in ASP.Net GridView using jQuery[^]


这篇关于选中/取消选中动态创建的gridview的所有复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆