【问题标题】:Error while Dynamically creating Checkbox Header template in GridView在 GridView 中动态创建复选框标题模板时出错
【发布时间】:2017-03-14 10:17:33
【问题描述】:

我使用 @Tim Schmelter 代码 (Creating Gridview column Header by loading data from database) 作为 ItemTemplate Checkboxes 它工作正常,但是当使用 HeaderTemplate 时,我在 ITemplate --> CB_DataBinding --> object dataValue = ((DataRowView)container.DataItem )[_columnName];说 NullReference,因为 DataItem 是 Null。我的代码:

private void CreateGridColumns()
        {
            var tblAllowanceGroup = GetAllowanceGroup();
            foreach (DataRow row in tblAllowanceGroup.Rows)
            { ...
              field.HeaderTemplate = new GridViewCheckBoxTemplate(ListItemType.Header, AllowanceGroupName);
              gvEmpSalaryStructure.Columns.Add(field);
            }
private void BindGrid()
        {
            var tblAllowanceGroup = GetAllowanceGroup();
            DataSet dsgrid = new DataSet();
            DataTable dtgrid = new DataTable();
            var empRow = dtgrid.NewRow();
            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
    //This gives me only Header Text of Gridview
                    }

我想要 GridView 动态生成的应该包含复选框的标题。并且想要更改我应该让 ITemplate CB_DataBinding 与 ListItemType.Header 一起使用。

当我们选中 Header 列中的复选框时,该列中的所有复选框都应该被选中。

提前致谢。

【问题讨论】:

    标签: c# asp.net sql-server-2008


    【解决方案1】:

    您可以使用gridview的OnRowDataBound事件循环标题行并在每个Cell中插入一个CheckBox。

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    CheckBox checkBox = new CheckBox();
                    checkBox.CssClass = "headerCheckBox";
                    checkBox.ID = "headerCheckBox_" + i;
                    e.Row.Cells[i].Controls.Add(checkBox);
                }
            }
        }
    

    现在您可以将 jQuery 侦听器绑定到 CheckBox 类来处理整个列的选中/取消选中。

    【讨论】:

      猜你喜欢
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 2019-06-16
      • 2019-06-22
      • 1970-01-01
      • 2015-05-31
      • 2013-01-25
      相关资源
      最近更新 更多