dynamically created button on datagrid is not firing item command

i have a datagrid in which i am dynamically creating template columns. the code i am using to create my delete button is as such..

      btn.Text = "Delete";
      btn.ID = "DeleteButton";
      btn.CommandName = "DeleteMe";
      container.Controls.Add(btn);
                  
the HTML for the datagrid is as such...

<asp:datagrid id=DataGrid1 Width="700px" runat="server" BorderStyle="None" BackColor="White" CellPadding="5" GridLines="Horizontal" AutoGenerateColumns="False" Font-Size="Smaller" Font-Names="Arial" BorderWidth="0px" ShowFooter="True" onItemCommand="DataGrid1_ItemCommand" onItemDataBound="DataGrid1_ItemDataBound" DataKeyField="pay_adjust_id" AllowSorting="True">



the datagrid displays and fills properly. but when i press the delete button, the page reloads and the datagrid is gone. when i debug, it never makes it to the onItemCommand function. Can someone help me figure out why the onItemCommand function is not firing? Thanks!
trevorayAsked:
Who is Participating?
 
trevorhartmanConnect With a Mentor Commented:
could you test by creating a button column and adding that to the datagrid, instead of creating a button and adding it to an existing colum?
0
 
trevorhartmanCommented:
Everything looks right.  Could something else be causing the problem?  Why would the datagrid be gone?  Where are you binding to the datagrid?

-Trevor
0
 
trevorayAuthor Commented:
Trevor,

I am binding the datagrid in a seperate function called BindGrid. I am calling this function at the end of my OnItemCommand function. Since the OnItemCommand never fires, not only does the row not get deleted, but datagrid doesn't get bound again on postback either. I'm sure something else could be causing the problem, but my problem is that I don't know what that something else is or how to find out what that something else is. Any ideas? Thanks!

Trevor
0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
trevorhartmanCommented:
can you post the code for your datagrid, your event handlers and the bindgrid function?
0
 
s_sansanwalCommented:
Instead of a Button, use a ButtonColumn
Write this code in Page_Load before binding the data grid

                  ButtonColumn btn = new ButtonColumn();
                  btn.ButtonType = ButtonColumnType.PushButton;
                  btn.Text = "Delete";
                  btn.CommandName = "DeleteMe";
                  this.DataGrid1.Columns.Add(btn);  


This will display a delete button in front of all rows and pressing them would fire DataGrid1_ItemCommand event
0
 
trevorayAuthor Commented:
i am creating a column dynamically. everything works great, except my delete button is not firing the onitemcommand.

if you can show me how to dynamically add a button column to my exisiting code, i will try it, but i don't think it would be compatable with how i have my code setup.

TemplateColumn tc5 = new TemplateColumn();
tc5.HeaderTemplate = new
DataGridTemplate(ListItemType.Header, "", 0, "text", "");
tc5.ItemTemplate = new
DataGridTemplate(ListItemType.Item, "pay_adjust_id", 35, "deletebutton", "mykey");
tc5.FooterTemplate = new
DataGridTemplate(ListItemType.Footer, "Footer Text", 5, "text", "");
tc5.ItemStyle.HorizontalAlign = HorizontalAlign.Right;

DataGrid1.Columns.Add(tc1);
DataGrid1.Columns.Add(tc2);
DataGrid1.Columns.Add(tc3);
DataGrid1.Columns.Add(tc4);
DataGrid1.Columns.Add(tc5);

public class DataGridTemplate : ITemplate
      {
            ListItemType templateType;
            string columnName;
            int textboxsize;
            string columntype;
            string textboxname;
            
            public DataGridTemplate(ListItemType type, string colname, int txtsize, string coltype, string txtname)
            {
                  templateType = type;
                  columnName = colname;
                  textboxsize = txtsize;
                  columntype = coltype;
                  textboxname = txtname;
                  

            }

            public void OnDataBinding(object sender, EventArgs e)
            {
                  
                  Type senderType = sender.GetType();
                  if (senderType == typeof(Literal))
                  {
                        /* do this */
                        Literal lc = (Literal) sender;
                        DataGridItem container = (DataGridItem) lc.NamingContainer;
                        lc.Text = ((DataRowView)container.DataItem)[columnName].ToString();
                  
                  }
                  else if (senderType == typeof(TextBox))
                  {
                        /* do this */
                        TextBox txt = (TextBox) sender;
                        DataGridItem container = (DataGridItem) txt.NamingContainer;
                        txt.Text = ((DataRowView)container.DataItem)[columnName].ToString();
                  }
                  


            }
            
            public void InstantiateIn(System.Web.UI.Control container)
            {
                  Literal lc = new Literal();
                  TextBox txt = new TextBox();
                  Button btn = new Button();    
                  switch(templateType)
                  {
                        case ListItemType.Header:
                              lc.Text = "<B>" + columnName + "</B>";
                              container.Controls.Add(lc);
                              break;
                        case ListItemType.Item:
                        switch(columntype)
                        {
                              case "text":
                                    txt.Columns = textboxsize;
                                    txt.DataBinding += new EventHandler(this.OnDataBinding);
                                    txt.ID = textboxname;
                                    container.Controls.Add(txt);
                                    break;
                              case "deletebutton":
                                    txt.ID = "mykey";
                                    txt.DataBinding += new EventHandler(this.OnDataBinding);
                                    txt.Visible = false;
                                    btn.Text = "Delete";
                                    btn.ID = "DeleteButton";
                                    btn.CommandName = "DeleteMe";
                                    container.Controls.Add(txt);
                                    container.Controls.Add(btn);
                                    break;
                        }
                              break;
                        case ListItemType.Footer:
                              lc.Text = "<I>" + columnName + "</I>";
                              container.Controls.Add(lc);
                              break;
                              
                  }
            }
      }
0
 
trevorhartmanCommented:
not sure how to add a button column with the setup that you have... sorry i couldn't help
-Trevor
0
 
s_sansanwalCommented:
removing if(Page.IsPostBack == false) condition from Page_Load function makes the event to fire properly
0
 
dlarlickCommented:

if you are using asp.net as I am assuming from the last comment check out the following.


   "Manage Dynamically Created Controls".

  http://devcenter.infragistics.com/Articles/ArticleTemplate.ASPX?ArticleID=2149

  see the "rember controls" section.

  If you're dynamically added controls are disappearing you do not have them added to the viewstate for the page to rerender the control on the postback.

  Not sure if this is what you're doing but good luck... It looks like you have alot of good feedback.

  -DLARLICK
0
 
rohanpandyaCommented:
when you add the button on the datagrid add following line to it

     test.EditCommand += new DataGridCommandEventHandler(doedit); here you can take any event

 it work's fine best luck


 Rohan
0
 
trevorayAuthor Commented:
ok, as a test, i added a button column to my code and it is performing exactly the same way.

dlarick, i don't think that article applies to my situation since the controls i am creating are being loaded on every page load.

0
 
dlarlickCommented:

Trevoray -

Are you recreating the control or is ASP recreating your control from the viewstate?

If ASP is recreating the control on postback you are doing things correctly and others are giving you appropriate feedback. (you are not doing an .add again)

However,  If your code runs again and you are re-adding the control yourself,  the article will address your issue in depth.


 
0
 
dlarlickCommented:
Ignore my last comment
0
 
trevorayAuthor Commented:
ok, this is the Itemplate class that allows dynamic datagrid template columns to be created. whenever i run the adding the template code in my main page class, it runs the functions from this code. this was from MSDN site. it all works fine my data is filled and everything. but i am not sure it is correctly assigning the command property for my delete button. anyone familiar with ITemplate that can help me figure out this solution? I do not want to add a button template column. Thank you.

public class DataGridTemplate : ITemplate
      {
            ListItemType templateType;
            string columnName;
            int textboxsize;
            string columntype;
            string textboxname;
            
            public DataGridTemplate(ListItemType type, string colname, int txtsize, string coltype, string txtname)
            {
                  templateType = type;
                  columnName = colname;
                  textboxsize = txtsize;
                  columntype = coltype;
                  textboxname = txtname;
                  

            }

            public void OnDataBinding(object sender, EventArgs e)
            {
                  
                  Type senderType = sender.GetType();
                  if (senderType == typeof(Literal))
                  {
                        /* do this */
                        Literal lc = (Literal) sender;
                        DataGridItem container = (DataGridItem) lc.NamingContainer;
                        lc.Text = ((DataRowView)container.DataItem)[columnName].ToString();
                  
                  }
                  else if (senderType == typeof(TextBox))
                  {
                        /* do this */
                        TextBox txt = (TextBox) sender;
                        DataGridItem container = (DataGridItem) txt.NamingContainer;
                        txt.Text = ((DataRowView)container.DataItem)[columnName].ToString();
                  }
                  
            }
            
            public void InstantiateIn(System.Web.UI.Control container)
            {
                  Literal lc = new Literal();
                  TextBox txt = new TextBox();
                  Button btn = new Button();    
                  switch(templateType)
                  {
                        case ListItemType.Header:
                              lc.Text = "<B>" + columnName + "</B>";
                              container.Controls.Add(lc);
                              break;
                        case ListItemType.Item:
                        switch(columntype)
                        {
                              case "text":
                                    txt.Columns = textboxsize;
                                    txt.DataBinding += new EventHandler(this.OnDataBinding);
                                    txt.ID = textboxname;
                                    container.Controls.Add(txt);
                                    break;
                              case "deletebutton":
                                    txt.ID = "mykey";
                                    txt.DataBinding += new EventHandler(this.OnDataBinding);
                                    txt.Visible = false;
                                    btn.Text = "Delete";
                                    btn.ID = "DeleteButton";
                                    btn.CommandName = "DeleteMe";
                                    container.Controls.Add(txt);
                                    container.Controls.Add(btn);
                                    break;
                        }
                              break;
                        case ListItemType.Footer:
                              lc.Text = "<I>" + columnName + "</I>";
                              container.Controls.Add(lc);
                              break;
                              
                  }
            }
      }
0
 
trevorayAuthor Commented:
also, thought i should show my HTML to prove that i have my OnItemCommand property set...

<asp:datagrid id=DataGrid1 Width="700px" runat="server" BorderStyle="None" BackColor="White" CellPadding="5" GridLines="Horizontal" AutoGenerateColumns="False" Font-Size="Smaller" Font-Names="Arial" BorderWidth="0px" ShowFooter="True" onItemCommand="DataGrid1_ItemCommand" onItemDataBound="DataGrid1_ItemDataBound" DataKeyField="pay_adjust_id" AllowSorting="True">
0
 
trevorayAuthor Commented:
i don't think there is a way around this except to hard code my delete column. closing out and giving points to trevor
0
 
dlarlickCommented:

Trevorary -
 
  can you provide your email address if you are still interested and I will communicate with you outside of this forum.

  I was playing around with nested datagrids and had a similiar problem.  

  Are you binding to your datagrid after the initialization method?

   
 
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.