2

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?

2
  • Why do you need AddToItemTemplate, do you have many controls to load? Commented Jul 21, 2014 at 14:25
  • no just the one, how can i do it without creating a template? Commented Jul 21, 2014 at 14:51

1 Answer 1

3

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")
   {
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.