EP - AX 2009 - Button per line in grid


 Say you want to perform an action on a line directly from the grid and not from a possible menu (working with the menu means you also have to actually select the line first): something like, opening for further action one invoice from a list of invoices presented in a grid.
 The solution mainly consists of:
 - adding an asp:TemplateField with an asp:ImageButton to the grid's fields list;
 - implement the grid's RowDataBound(object sender, GridViewRowEventArgs e) in order to add to the button's attributes list  the value of the line's recId or some other primary index value;
 - implement the action on the button's OnClick.

Now, for some of the code:


1. in the .ascx file, in the grid's columns list:

         <asp:TemplateField ConvertEmptyStringToNull="False">
            <ItemTemplate>
                <asp:ImageButton ID="ImageButtonCommentInvoice" runat="server" AlternateText="Select" OnClick="ImageButtonCommentInvoice_Click"
                    Style="cursor: pointer;" /></ItemTemplate>
            <EditItemTemplate>
                <asp:ImageButton ID="ImageButtonCommentInvoice" runat="server" AlternateText="Select" OnClick="ImageButtonCommentInvoice_Click"
                    Style="cursor: pointer;" /></EditItemTemplate>
            <ItemStyle VerticalAlign="Top" />
        </asp:TemplateField>       


2. in the code behind file:

    void  gridInvoicesList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row != null && e.Row.RowType == DataControlRowType.DataRow
            && e.Row.DataItem != null)
        {
            DataSetViewRow dataRow = (DataSetViewRow)e.Row.DataItem;
            ImageButton currentButton;

            currentButton = e.Row.Cells[ButtonIndex].Controls[1] as ImageButton;

            if (currentButton == null)
                return;

            currentButton.Attributes["InvoiceId"] = dataRow.GetFieldValue("InvoiceId").ToString();
            currentButton.ImageUrl = @"/_layouts/ep/images/an image.gif";
        }
    }


    protected void ImageButtonCommentInvoice_Click(object sender, EventArgs e)
    {
        ImageButton currentButton = sender as ImageButton;
        if (currentButton == null)
            return;

        // TODO add some logic with currentButton.Attributes["InvoiceId"].ToString();

    }
 

1 comment:

  1. currentButton.Attributes["InvoiceId"].ToString() give the null object exception , any ideas?

    ReplyDelete