![](/img/trans.png)
[英]Dynamically create item template hyperlink field in gridview ASP.NET
[英]asp.net create Gridview item template dynamically with button click
asp.net 4.0表格。
我需要使用鏈接到表ID鍵的按鈕動態創建Gridview。
因此,我設置了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);
....
然后創建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
}
我將我的ID收集在GV_RowDataBound中,並在圖像按鈕命令參數中進行設置,沒有問題。
一切正常,但是方法ib_Command是靜態的,因為它是ITemplate的一部分。 我無法訪問任何頁面控件或任何頁面實例變量。
當在ASPX標記文件中創建gridviews時,有沒有辦法將按鈕(ib.command + =)鏈接到任何頁面方法,就像使用“ oncommand”標記完成的那樣?
根據您的代碼和注釋,您嘗試將圖像按鈕列添加到Gridview。 為此,您不需要創建新的模板。 相反,您可以按如下所示添加ButtonField
ButtonField buttonField = new ButtonField();
buttonField.ButtonType = ButtonType.Image;
buttonField.ImageUrl = "~/Images/bullet.png";
buttonField.CommandName = "delete";
GV.Columns.Add(buttonField);
現在,在gridview的RowCommand事件中,您可以執行所需的操作
protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName=="delete")
{
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.