[英]asp.net create Gridview item template dynamically with button click
asp.net 4.0 forms. asp.net 4.0表格。
I need to create a Gridview Dynamically with a button linked to the table ID Key. 我需要使用链接到表ID键的按钮动态创建Gridview。
So I set up the Gridview and start adding columns: 因此,我设置了Gridview并开始添加列:
private void SetupGV()
{
try
{ //0
TemplateField tf = new TemplateField();
tf.HeaderText = "X";
tf.ItemTemplate = new AddToItemTemplate();
GV.Columns.Add(tf);
//1
BoundField b = new BoundField();
b.DataField = "FullName";
b.HeaderText = @"Staff / Role";
GV.Columns.Add(b);
....
then I create the ITemplate AddToItemTemplate: 然后创建ITemplate AddToItemTemplate:
public class AddToItemTemplate : ITemplate
{
public AddToItemTemplate(){}
public void InstantiateIn(Control container)
{
ImageButton ib = new ImageButton();
ib.ImageUrl = "~/Content/CIDimg/action4.gif";
ib.Command += ib_Command;
ib.CommandName = "delete";
container.Controls.Add(ib);
}
void ib_Command(object sender, CommandEventArgs e)
{
string s = e.CommandArgument.ToString();
}
#endregion
}
I collect my ID in GV_RowDataBound and set it in the image button command argument no problem there. 我将我的ID收集在GV_RowDataBound中,并在图像按钮命令参数中进行设置,没有问题。
It all works fine but the method ib_Command is Static as it is part of the ITemplate. 一切正常,但是方法ib_Command是静态的,因为它是ITemplate的一部分。 I cannot access any page control nor any page instance variables.
我无法访问任何页面控件或任何页面实例变量。
Is there a way to link the button (ib.command +=) to any of the page methods like it is done with the "oncommand" tag when gridviews are created in ASPX markup file? 当在ASPX标记文件中创建gridviews时,有没有办法将按钮(ib.command + =)链接到任何页面方法,就像使用“ oncommand”标记完成的那样?
Based on your code, and comments, you are trying to add an image button column to the Gridview. 根据您的代码和注释,您尝试将图像按钮列添加到Gridview。 For this you do not need to create a new Template.
为此,您不需要创建新的模板。 Instead you can add ButtonField as below
相反,您可以按如下所示添加ButtonField
ButtonField buttonField = new ButtonField();
buttonField.ButtonType = ButtonType.Image;
buttonField.ImageUrl = "~/Images/bullet.png";
buttonField.CommandName = "delete";
GV.Columns.Add(buttonField);
Now in on the RowCommand event of the gridview you can perform the required actions 现在,在gridview的RowCommand事件中,您可以执行所需的操作
protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName=="delete")
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.