Проверьте/ снимите все флажки динамически создаваемого gridview
У меня есть два выпадающих списка и элемент управления Gridview на моей странице aspx. Все столбцы gridview динамически генерируются в соответствии с выбором пользователя из выпадающих списков.
Gridview содержит 2 связанных поля и N шаблонных полей, содержащих флажки. Граничные поля являются постоянными, а количество шаблонных полей изменяется в зависимости от выбора выпадающего списка. Флажки создаются с помощью Itemplate.
Теперь мне нужно установить флажок снять все флажки столбца gridview, когда установлен флажок в заголовке Gridview.
Я добавил событие CheckedChanged в Itemplate, которое также не вызывает этот метод. Пожалуйста, помогите мне. Вот мой код:
Умолчанию.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>  <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>  <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 + " "; 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'"; }
Что я уже пробовал:
Я попытался добавить событие в флажок в заголовке Itemplate. но это событие не называется.