asp.net动态创建Gridview项目模板,点击按钮

时间:2014-07-21 14:03:56

标签: c# asp.net gridview itemplate

asp.net 4.0表格。

我需要使用链接到表ID Key的按钮动态创建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
    }          

我在GV_RowDataBound中收集我的ID并在图像按钮命令参数中设置它没有问题。

一切正常,但 ib_Command 方法是静态的,因为它是ITemplate的一部分。 我无法访问任何页面控件或任何页面实例变量。

有没有办法将按钮(ib.command + =)链接到任何页面方法,就像在ASPX标记文件中创建网格视图时使用“oncommand”标记一样?

1 个答案:

答案 0 :(得分:3)

根据您的代码和注释,您尝试将图像按钮列添加到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")
   {
   }
}
相关问题