日期:2014-05-18  浏览次数:20357 次

GridView动态创建TemplateField的问题
GridView动态创建TemplateField,TemplateField.ItemTemplate中是一些文本信息,在页面回调后TemplateField.ItemTemplate的内容消失了,我想保留这些信息,请问怎么处理?

------解决方案--------------------
你在什么地方动态创建GridView的TemplateField?Page_Load()?
把代码放到OnInit()里面去.
ViewState在Page_Load()之前就LOAD了,所以要在OnInit()里就要动态加列.
------解决方案--------------------
动态添加摸版列并将值绑定到label中的例子

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// GridViewTemplate 的摘要说明
/// </summary>
public class GridViewTemplate:ITemplate
{
private DataControlRowType templateType;
private string columnName;

public GridViewTemplate(DataControlRowType type, string colname){

templateType = type;
columnName = colname;
}

public void InstantiateIn(System.Web.UI.Control container){

if(templateType == DataControlRowType.DataRow){

LiteralControl label = new LiteralControl();

label.DataBinding += new EventHandler(tb_DataBinding);
container.Controls.Add(label);
}
}

private void tb_DataBinding(object sender, EventArgs e)
{
LiteralControl lb = (LiteralControl)sender;
GridViewRow container = (GridViewRow)lb.NamingContainer;
string str = ((DataRowView)container.DataItem)[columnName].ToString();
lb.Text = GetChange(str,columnName);//自定义的用于显示的方法
}
}
}
------解决方案--------------------
public class SelectionField : DataControlField
{
public SelectionField()
{

}

protected override DataControlField CreateField()
{
return new SelectionField();
}

public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
{
base.InitializeCell(cell, cellType, rowState, rowIndex);
if (cellType == DataControlCellType.DataCell)
{
CheckBox chkBox = new CheckBox();
chkBox.ID = "chkBox ";
cell.Controls.Clear();
cell.Controls.Add(chkBox);
}
}
}
}

public class TLGridView : GridView, INamingContainer
{


protected override ICollection CreateColumns(PagedDataSource dataSource, bool useDataSource)
{
ICollection cols = base.CreateColumns(dataSource, useDataSource);
SelectionField selection = new SelectionField ();

cols .Insert(0, selection);


}

return cols;
}
}