C# 如何以编程方式添加 TemplateField
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12581088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add TemplateField programmatically
提问by Arian
please consider this code:
请考虑以下代码:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="linkmodel" Text='<%#Eval("MenuItem") %>'
CommandName='<%#Eval("CommandName") %>'
OnCommand="linkmodel_Click"
OnClientClick="return confirm('Are You Sure')">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
How to add this column programmatically using C#?
如何使用 C# 以编程方式添加此列?
thanks
谢谢
采纳答案by Tim Schmelter
This might help to get started:
这可能有助于开始:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var linkField = new TemplateField();
linkField.ItemTemplate = new LinkColumn();
GridView1.Columns.Add(linkField);
}
}
class LinkColumn : ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
LinkButton link = new LinkButton();
link.ID = "linkmodel";
container.Controls.Add(link);
}
}
But:
但是:
Although you can dynamically add fields to a data-bound control, it is strongly recommendedthat fields be statically declared and then shown or hidden, as appropriate. Statically declaring all your fields reduces the size of the view state for the parent data-bound control.
尽管您可以向数据绑定控件动态添加字段,但 强烈建议静态声明字段,然后根据需要显示或隐藏字段。静态声明所有字段会减少父数据绑定控件的视图状态的大小。
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield.templatefield.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield.templatefield.aspx

