ASP.Net Gridview how to make entire row a link

by Joe Payne 6. Augustus 2012 10:19

I found this today and was completely floored in it’s simplicity.  Works like a charm:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string ProductId = DataBinder.Eval(e.Row.DataItem, "ProductId").ToString();
            string Location = ResolveUrl("~/Details.aspx") + "?ProductId=" + ProductId ;
            e.Row.Attributes["onClick"] = string.Format("javascript:window.location='{0}';", Location);
            e.Row.Style["cursor"] = "pointer";
        }
    }

Tags: , , ,

AC7 Articles | Personal

AbleCommerce how to handle sorting of GridView control

by Joe Payne 18. Januarie 2012 23:25

Introduction

This article talks about manually handling the sorting routine of a GridView control.   When using an object class as the Datasource for a GridView control in AbleCommerce, the GridView control will not automatically manage sorting.  This only works when using a SQL-based DataSourceObject.

So you’re left with creating your own method to handle the Sorting event on the GridView control.  Not so tough, there’s plenty of programming code examples in Google.   What’s harder to find is an example that actually retains the previous sort order for each column.

Enter:  e.SortDirection.  It’s exposed in the Sorting event, but you need a way to store the previous sort order for each column so the routine knows which way to flip it (Ascending or Descending).  If you don’t handle it, clicking a column always results in an Ascending sort order.

Here’s a good piece of code that makes nice use of Viewstate:

protected void ProductsGrid_Sorting(object sender, GridViewSortEventArgs e)
{
    if (e.SortExpression == (string)ViewState["SortColumn"])
    {
        // We are resorting the same column, so flip the sort direction
        e.SortDirection =
            ((SortDirection)ViewState["SortColumnDirection"] == SortDirection.Ascending) ?
            SortDirection.Descending : SortDirection.Ascending;
    }
    // Apply the sort
    BindProductsGrid(e.SortExpression, ConvertSortDirection(e.SortDirection));
    ViewState["SortColumn"] = e.SortExpression;
    ViewState["SortColumnDirection"] = e.SortDirection;
 
}

Tags: , ,

AC7 Articles

Control an ASP.Net Modal Popup within a Gridview Row

by Joe Payne 22. Junie 2011 14:47

So today I needed to do something I had done before.  Simple, right?  Just copy/paste the code from another project and <wham> everything works, right?  NOT!

Today’s goal was to make a popup edit window for the contents of a specific grid row.  Each gridview row has it’s own edit button.  I want the user to be able to edit the controls of the gridview row within a nifty popup window.

First we have to add a Panel to our HTML.  This panel will contain everything included in our popup window.  Here’s a good start:

<asp:Panel ID="EditReturnItemDialog" runat="server" Style="display: none; width: 300px" CssClass="modalPopup">
    <asp:Panel ID="EditReturnItemDialogHeader" runat="server" CssClass="modalPopupHeader" EnableViewState="false">
        <asp:Localize ID="EditReturnItemDialogCaption" runat="server" Text="Edit Return Item" EnableViewState="false"></asp:Localize>
    </asp:Panel>
    <br />
    Specify Return Number for this return...
    <br /><br />
    <table>
        <tr valign="middle" style="font-weight:bold">
            <td>Return Number: </td>
            <td><asp:TextBox ID="txt_AuthorizeReturnNumber" runat="server" Width="80px"/></td>
        </tr>
        </table>
    <br /><br />
    <center><asp:Button ID="btn_SaveEditReturnItem" runat="server" Text="Submit" OnClick="btn_SaveEditReturnItem_Click"/>&nbsp;&nbsp;&nbsp;<asp:Button ID="btn_EditReturnItemCancel" runat="server" Text="Cancel" /></center>
</asp:Panel>

Notice the object ID names here.  They are critical and must match exactly with how you specify them in the ModalPopupExtender.  If you get just one wrong, the popup won’t fire and you may not even see an error depending on how your browser is configured.

Also notice at the end of the panel is a save button with an OnClick event, but the Cancel button does not have one.  This is intentional.  Unless you have need to extra functionality within the Cancel operation, you can hook the ‘cancel’ functionality of the MPE directly to the button.  Alternatively you can specify an OnClick event for the Cancel button and specifically issue the MPE.Hide() command.  It’s your choice.

Once your Panel is in place, now it’s time to build the ModalPopupExtender itself.  Here how this one will look:
<ajax:ModalPopupExtender ID="mpe_EditReturnItemPopup" runat="server" TargetControlID="btn_Hidden1"
PopupControlID="EditReturnItemDialog" BackgroundCssClass="modalBackground" CancelControlID="btn_EditReturnItemCancel"
DropShadow="false" PopupDragHandleControlID="EditReturnItemDialogHeader" />

There’s a lot here, but basically it all makes sense.  We give the MPE an ID for itself.  But notice the TargetControlId is set to an object we haven’t added yet.  That object, btn_Hidden1 is the trick.  Normally an MPE requires being hooked into a working button.  That’s what we’re doing here, we’ve just made the button invisible. 

By setting an MPE to a button that isn’t used, it gives you the ability to create an MPE and manually manipulate it elsewhere in the code-behind.  Here’s the code for the hidden button, it’s quite simple:

<asp:Button ID="btn_Hidden1" runat="server" style="display: none"  />

Note how I’ve used a style with display: none instead of the usual Visible=”false”.  Why?  Because a Visible=”false” will not render the control at all on the client side, thus the MPE cannot find it’s button to hook.  The MPE will fail to fire the popup and it’s doubtful you’ll even see an error.  So do not use the Visible=, instead use a style with display: none on your hidden button.

We have one last thing to build on the HTML side:  Our gridview command button.  This button renders for each row in the Gridview control.  It’s responsible for opening the actual popup window when it’s clicked.

Adding the button is easily done.  Simply add the button to a template field in your gridview row like such:

<asp:TemplateField HeaderText="Actions">
    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
    <ItemTemplate>
        <asp:LinkButton ID="btn_Edit" runat="server" ToolTip="Edit" CommandName="Do_Edit" CommandArgument='<%#string.Format("{0}", Eval("ReturnItemId"))%>'><img src="<%# GetIconUrl("edit.gif") %>" 
        border="0" alt="Edit" /></asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField>

In this particular case, we’re using an icon image to represent the button but you get the point nonetheless.

The key here is we’re using the gridview RowCommand event to handle the popup action.  So the button must have the CommandName and CommandArgument parameters specified.

Finally we’re done with the HTML side.  Now let’s build the code-behind to drive this popup.

For your Gridview control, make sure you’ve specified a function for the RowCommand event like so:

<asp:GridView ID="grd_ReturnItems" runat="server" AutoGenerateColumns="False" DataKeyNames="ReturnItemId"
    CellSpacing="0" CellPadding="4" Width="100%" SkinID="Summary" OnRowCommand="grd_ReturnItems_RowCommand" >

Now build the code-behind to drive the ModalPopupExtender and render the popup.  Here’s the final piece of the puzzle:

Protected Sub grd_ReturnItems_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grd_ReturnItems.RowCommand
 
    ' pull in the ReturnItemID and load up the returnitem class
    Dim _ReturnItemId As Integer = AlwaysConvert.ToInt(e.CommandArgument)
    Dim _ReturnItem As ReturnItem = ReturnItemsDataSource.Load(_ReturnItemId)
    If _ReturnItem.ReturnItemid = 0 Then
        Return
    End If
 
    Select Case e.CommandName
        Case "Do_Edit"
            mpe_EditReturnItemPopup.Show()
    End Select
 
End Sub

See how it’s done?  Simply call the .Show() method of the ModalPopupExtender object.  The browser client handles the rest automatically.

Well if you’ve read this far, then you’ve probably realized by now that I never answered the question of “Why didn’t it work when you copy/paste’d the code from another project?”  I made the mistake of using Visible=”False” on the hidden button instead of using style=”display: none” </thumpsforehead> Smile

Tags: , , , ,

AC7 Articles | Personal | Tech Support

Month List