GridView动态创建模板列,在绑定时出现错误!
//模板列
public class LabelItemTemplate : ITemplate
{
public LabelItemTemplate(string ID, string ColumnName)
{
id = ID;
columnName = ColumnName;
}
public void InstantiateIn(Control Container)
{
Label lbl = new Label();
lbl.ID = id;
lbl.DataBinding += new EventHandler(this.OnDataBinding);
Container.Controls.Add(lbl);
}
public void OnDataBinding(object sender, EventArgs e)
{
Label lbl = (Label)sender;
GridViewRow container = (GridViewRow)lbl.NamingContainer;
((DataRowView)container.DataItem)[columnName].ToString();
}
}
//创建模板列
TemplateField tmp = new TemplateField();
tmp.ItemTemplate = new LabelItemTemplate( "1 ", "Field1 ");
GridView.Columns.Add(tmp);
//生成数据
DataTable dt = new DataTable();
for(int i=0; i <20; i++)
{
DataRow row = dt.NewRow();
分别设置列的指....
dt.Rows.Add(row);
}
//绑定数据
GridView.DataSource = dt;
GridView.DataBind();
//运行到GridView.DataBind();就粗错:提示
提示ArgumentNullException: 值不能为空。参数名: propName
System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName)
System.Web.UI.WebControls.GridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding)
....
....
//如果不生成行,就不会报错!
//起初以为问题出在模板列的绑定上,就把
//((DataRowView)container.DataItem)[columnName].ToString();
//这句注释掉,结果还是报同样的错误.
//不知道是什么原因.
请大家帮忙!
------解决方案--------------------// 以下代码测试通过, !!! 部分是我添加的代码
<%@ Page Language= "C# " %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<script runat= "server ">
//模板列
public class LabelItemTemplate : ITemplate
{
private string id, columnName;
public LabelItemTemplate(string ID, string ColumnName)
{
id = ID;
columnName = ColumnName;
}
public void InstantiateIn(Control Container)
{
Label lbl = new Label();
lbl.ID = id;
lbl.DataBinding += new EventHandler(this.OnDataBinding);
Container.Controls.Add(lbl);
}
public void OnDataBinding(object sender, EventArgs e)
{
Label lbl = (Label)sender;
GridViewRow container = (GridViewRow)lbl.NamingContainer;
// ((DataRowView)container.DataItem)[columnName].ToString();
lbl.Text = ((DataRowView)