如何以编程方式添加gridview的itemtemplate自定义控件
1个回答
展开全部
动态添加模板列
public class GridViewTextTemplate : System.Web.UI.ITemplate
{
private DataControlRowType templateType;
private string columnName;
private string Id;
public GridViewTextTemplate(DataControlRowType type, string colname, string controlId)
{
templateType = type;
columnName = colname;
Id = controlId;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (templateType)
{
case DataControlRowType.Header:
myHeadLiteral.ID = Id;
myHeadLiteral.Text = columnName;
container.Controls.Add(myHeadLiteral);
break;
case DataControlRowType.DataRow:
TextBox txt= new TextBox();
txt.ID = cId;
txt.DataBinding += new EventHandler(this.TextBoxDataBinding);
container.Controls.Add(txt);
break;
default:
break;
}
}
private void TextBoxDataBinding(Object sender, EventArgs e)
{
TextBox txt= (TextBox)sender;
GridViewRow row = (GridViewRow)txt.NamingContainer;
txt.Text = System.Web.UI.DataBinder.Eval(row.DataItem, columnName).ToString();
}
}
void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
TemplateField tf;
tf= new TemplateField();
tf.ItemTemplate = new GridViewTextTemplate(DataControlRowType.DataRow, "", "");
tf.HeaderTemplate = new GridViewTextTemplate(DataControlRowType.Header, "", "");
GridView1.Columns.Add(tf);
}
}
public class GridViewTextTemplate : System.Web.UI.ITemplate
{
private DataControlRowType templateType;
private string columnName;
private string Id;
public GridViewTextTemplate(DataControlRowType type, string colname, string controlId)
{
templateType = type;
columnName = colname;
Id = controlId;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (templateType)
{
case DataControlRowType.Header:
myHeadLiteral.ID = Id;
myHeadLiteral.Text = columnName;
container.Controls.Add(myHeadLiteral);
break;
case DataControlRowType.DataRow:
TextBox txt= new TextBox();
txt.ID = cId;
txt.DataBinding += new EventHandler(this.TextBoxDataBinding);
container.Controls.Add(txt);
break;
default:
break;
}
}
private void TextBoxDataBinding(Object sender, EventArgs e)
{
TextBox txt= (TextBox)sender;
GridViewRow row = (GridViewRow)txt.NamingContainer;
txt.Text = System.Web.UI.DataBinder.Eval(row.DataItem, columnName).ToString();
}
}
void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
TemplateField tf;
tf= new TemplateField();
tf.ItemTemplate = new GridViewTextTemplate(DataControlRowType.DataRow, "", "");
tf.HeaderTemplate = new GridViewTextTemplate(DataControlRowType.Header, "", "");
GridView1.Columns.Add(tf);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询