Solved

dynamically created button on datagrid is not firing item command

Posted on 2004-08-09
17
729 Views
Last Modified: 2008-01-09
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!
0
Comment
Question by:trevoray
  • 6
  • 4
  • 4
  • +2
17 Comments
 
LVL 8

Expert Comment

by:trevorhartman
ID: 11757307
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
 

Author Comment

by:trevoray
ID: 11757429
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
 
LVL 8

Expert Comment

by:trevorhartman
ID: 11757458
can you post the code for your datagrid, your event handlers and the bindgrid function?
0
 
LVL 8

Accepted Solution

by:
trevorhartman earned 500 total points
ID: 11757485
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
 
LVL 9

Expert Comment

by:s_sansanwal
ID: 11757504
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
 

Author Comment

by:trevoray
ID: 11757511
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
 
LVL 8

Expert Comment

by:trevorhartman
ID: 11757836
not sure how to add a button column with the setup that you have... sorry i couldn't help
-Trevor
0
 
LVL 9

Expert Comment

by:s_sansanwal
ID: 11757859
removing if(Page.IsPostBack == false) condition from Page_Load function makes the event to fire properly
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 2

Expert Comment

by:dlarlick
ID: 11759181

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
 
LVL 4

Expert Comment

by:rohanpandya
ID: 11762899
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
 

Author Comment

by:trevoray
ID: 11763000
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
 
LVL 2

Expert Comment

by:dlarlick
ID: 11763229

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
 
LVL 2

Expert Comment

by:dlarlick
ID: 11763305
Ignore my last comment
0
 

Author Comment

by:trevoray
ID: 11765218
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
 

Author Comment

by:trevoray
ID: 11765288
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
 

Author Comment

by:trevoray
ID: 11767484
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
 
LVL 2

Expert Comment

by:dlarlick
ID: 11767806

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

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now