【问题标题】:Dynamic Gridview column not found on postback回发时未找到动态 Gridview 列
【发布时间】:2014-09-03 14:39:17
【问题描述】:

我有一个网格视图,其中的列是动态添加的。然而,在回发时,这些列不再存在。

我知道动态创建的项目必须在回发、调试时重新创建,即使创建列代码已成功执行,但 gridview 不包含任何列。

 protected void gvUsers_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {    //creating column 
            List<Module> listModule = getModules();
                foreach (Module m in listModule)
                {
                    TemplateField tfield = new TemplateField();
                    tfield.HeaderTemplate = new TickColumn(m.ModuleName);        
                    gvUsers.Columns.Add(tfield);
                }
        }


        if (e.Row.RowType == DataControlRowType.DataRow)
        { //Creation of checkboxes in the dynamic columns
             List<Module> listModule = getModules();
            int i = 3; // cell postioning
            foreach (Module m in listModule)
            {
                CheckBox cbActive = new CheckBox();
                cbActive.ID = m.ModuleID.ToString();
                e.Row.Cells[i].Controls.Add(cbActive); //Error<- because the cell does not have the column
                i++;
            }
        }
    }

我是否在错误的事件中创建了列?

【问题讨论】:

  • 这不应该在数据绑定事件中吗?
  • 之所以放在RowCreateEvent中是因为This。查看蒂姆的答案

标签: c# asp.net gridview


【解决方案1】:
if (e.Row.RowType == DataControlRowType.Header)
    {    //creating column 
        List<Module> listModule = getModules();
            foreach (Module m in listModule)
            {
                TemplateField tfield = new TemplateField();
                tfield.HeaderTemplate = new TickColumn(m.ModuleName);        
                tfield.Controls.Add(cbActive);
                CheckBox cbActive = new CheckBox();
                cbActive.ID = m.ModuleID.ToString();
                gvUsers.Columns.Add(tfield);
            }
    }

}

试试上面的代码,我还没有编译代码,但知道怎么做,

【讨论】:

  • 复选框的创建是针对数据行的,而不是针对标题的。创建代码很好。我怀疑它的事件,由于某种原因它正在刷新刚刚创建的列,使其在回发时再次为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 2014-10-22
  • 1970-01-01
相关资源
最近更新 更多