Lambda
Lambda

Reputation: 1640

asp.net create Gridview item template dynamically with button click

asp.net 4.0 forms.

I need to create a Gridview Dynamically with a button linked to the table ID Key.

So I set up the Gridview and start adding columns:

   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:

    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.

It all works fine but the method ib_Command is Static as it is part of the 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?

Upvotes: 2

Views: 3493

Answers (1)

Kiran Hegde
Kiran Hegde

Reputation: 3681

Based on your code, and comments, you are trying to add an image button column to the Gridview. For this you do not need to create a new Template. Instead you can add ButtonField as below

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

protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
{
   if (e.CommandName=="delete")
   {
   }
}

Upvotes: 3

Related Questions