Click here to Skip to main content
Licence Apache
First Posted 9 Aug 2007
Views 141,541
Downloads 593
Bookmarked 37 times

ASP.NET GridView Image Command Button Problem (Multiple PostBacks)

By | 10 Oct 2008 | Article
This article describes workarounds to solve the problem of multiple postbacks when using a command button of type image in an ASP.NET GridView (Internet Explorer).

Last update: 2008-10-10 Updated template solution

To run the application, download and unzip it to a folder on your computer and open it with Visual Studio 2005 (Pro or Web Edition) and run it over the development server.

Screenshot - Running.gif

Introduction

I ran into the problem that my page was loaded twice after selecting a row in a GridView by clicking on a CommandField with Type equal to Image. I found out that two requests were sent from the client: the first request is not a PostBack request on my page (this is the request I didn't expect; the second request is a PostBack request on my page (this is the request I expected).

If something is completely strange, then I always check it in FireFox and to no much surprise, there is only one request (the expected PostBack request). Therefore I also checked it with Internet Explorer 6 and there the problem occurs once in about 4 times!?!?

To sum it up:

  • Internet Explorer 7: Always 2 requests
  • Internet Explorer 6: Sometimes it's okay, sometimes not
  • FireFox: Everything works correctly

Note: This behaviour is only present when using Image as type of the CommandField, with Link or Button, everything works great.

How I Would Do It When Everything Would Be Correct

The following ASPX definition shows a GridView with a CommandButton of type image:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataSourceID="ObjectDataSource1" 
    OnSelectedIndexChanged="SelectedIndexChanged">
    <Columns>
        <asp:CommandField ButtonType="Image" 
             SelectImageUrl="~/Select.gif" ShowSelectButton="True" />
        <asp:BoundField DataField="A" HeaderText="A" SortExpression="A" />
        <asp:BoundField DataField="B" HeaderText="B" SortExpression="B" />
        <asp:BoundField DataField="C" HeaderText="C" SortExpression="C" />
    </Columns>
</asp:GridView>  

This GridView results in the problems I described in the introduction. Although, I really don't understand what could go wrong here, it simply doesn't work. If you compare the generated HTML for a GridView with a CommandButton of type Link and one of type Image, then you'll see that nothing is really different - except that once there will be only one request and once there will be two!

I spent some time Googling and found some workarounds. I assembled all the information that I found and show you in the following sections three workarounds along with their advantages and disadvantages.

Solution 1 - Use CommandButton of Type Link and Add the Image as HTML in the Link Text

This is the simplest workaround. I simply change the type of the CommandButton to be Link instead of Image and set the Text property to some HTML that will show the image:

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" 
    DataSourceID="ObjectDataSource1">
    <Columns>
        <asp:CommandField ShowSelectButton="True" 
            SelectText="<img src='Select.gif' border=0 title='This is a Tooltip'>">
        </asp:CommandField>
        <asp:BoundField DataField="A" HeaderText="A" SortExpression="A" />
        <asp:BoundField DataField="B" HeaderText="B" SortExpression="B" />
        <asp:BoundField DataField="C" HeaderText="C" SortExpression="C" />
    </Columns>
</asp:GridView>

This works great but has one disadvantage: the localization of the tooltip text gets difficult. The whole HTML string has to be added to the local resource, which isn't quite nice.

Solution 2 - Switch to TemplateFields

To get a solution that is better localizable, I delete the CommandField column and add a template column that contains an ImageButton. To get the same behaviour, the CommandName has to be set to "Select".

<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" 
    DataSourceID="ObjectDataSource1">
    <Columns>
        <asp:TemplateField ShowHeader="false">
            <ItemStyle HorizontalAlign="Center" />
            <ItemTemplate>
                <asp:ImageButton ID="btnView" runat="server" 
                    CausesValidation="False" CommandName="Select"
                    ImageUrl="~/Select.gif" ToolTip="View" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="A" HeaderText="A" SortExpression="A" />
        <asp:BoundField DataField="B" HeaderText="B" SortExpression="B" />
        <asp:BoundField DataField="C" HeaderText="C" SortExpression="C" />
    </Columns>
</asp:GridView>

Custom Commands Sample

In order to get your custom commands to work, you can either use a ButtonField with ButtonType equal to Link and use the same trick to display the image as in solution 1 or use a template field as in solution 2. I prefer solution 2, but be sure that you include the CommandArgument in the definition, otherwise you won't have access to the row index.

The following sample shows this together with the approaches that do not work (see Tooltip for explanation as to what happens):

<asp:GridView ID="GridView4" runat="server" AutoGenerateColumns="False" 
              DataSourceID="ObjectDataSource1" OnRowCommand="RowCommand">
    <Columns>
        <asp:ButtonField ButtonType="Image" CommandName="MyCommand1" 
                         ImageUrl="~/Select.gif"
                         Text="Double PostBack in IE7 (sometimes in IE6)" />
        <asp:TemplateField ShowHeader="False">
            <ItemStyle HorizontalAlign="Center" />
            <ItemTemplate>
                <asp:ImageButton ID="btnView" runat="server" CausesValidation="False"
                                 CommandName="MyCommand2"
                                 CommandArgument="<%# Container.DataItemIndex %>"
                                 ImageUrl="~/Select.gif" 
                                 ToolTip="Works! Preferred solution." />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:ButtonField ButtonType="Link" CommandName="MyCommand3" 
            Text="<img src='Select.gif' border=0 title='Works! But bad localizable.'>"
        />
        <asp:BoundField DataField="A" HeaderText="A" SortExpression="A" />
        <asp:BoundField DataField="B" HeaderText="B" SortExpression="B" />
        <asp:BoundField DataField="C" HeaderText="C" SortExpression="C" />         
    </Columns>
</asp:GridView>

Conclusion

There exists a problem in Internet Explorer that leads to multiple PostBacks when using a CommandButton with type Image. As long as this bug isn't fixed (or everybody uses FireFox;-)), we have to use some workarounds. In this article, I showed you three workarounds along with the scenario in which you can use them. In short: if you use template fields, you're always on the safe side.

If you have further information or other/better workarounds or even real solutions, then PLEASE post them below!!

History

  • 2007-08-09 Initial version
  • 2008-10-10 Changed template fields solution as proposed by Petr Behensky in his message post 

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0

About the Author

Urs Enzler

Architect
bbv Software Services AG
Switzerland Switzerland

Member

Urs Enzler is working for bbv Software Services in Switzerland as a Software Architect.
 
Blogger at planetgeek.ch

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
AnswerSolution PinmemberZaibot5:57 22 Nov '10  
GeneralGenius PinmemberLechu8117:48 16 Nov '10  
GeneralMy vote of 5 PinmemberJeff Allegi5:23 23 Oct '10  
GeneralA little problem with gridview PinmemberMarcel OUEDRAOGO6:26 1 Apr '10  
GeneralThanks PinmemberBilly Camargo16:27 4 Mar '10  
Generalthanks Pinmemberonurand6:27 20 Feb '10  
GeneralRe: thanks PinmemberUrs Enzler2:32 21 Feb '10  
GeneralThank you very much Pinmembermehdi_javan23:57 8 Nov '09  
GeneralRe: Thank you very much PinmemberUrs Enzler22:52 18 Nov '09  
GeneralVery simple! Pinmemberjomree22:00 3 Nov '09  
GeneralRe: Very simple! PinmemberUrs Enzler22:53 18 Nov '09  
GeneralThe Magic Pinmembermhenrique8:05 15 Oct '09  
GeneralAnother work around Pinmemberaida_dizdar22:21 7 Jun '09  
GeneralDouble postback causes AJAX to hang PinmemberJOZS22:06 26 Feb '09  
JokeThank you very much! Pinmemberzambizi1:18 9 Oct '08  
GeneralRe: Thank you very much! PinmemberUrs Enzler12:37 10 Oct '08  
Generaltemplate works well PinmemberPetr Behensky23:05 29 Sep '08  
You only have to set CommandArgument to the rowId. After that you can work with RowComand event as like for other Fields.
    <asp:gridview id="GridView3" runat="server" autogeneratecolumns="False" xmlns:asp="#unknown">
        DataSourceID="ObjectDataSource1">
        <columns>
            <asp:templatefield showheader="false">
                <itemstyle horizontalalign="Center" />
                <itemtemplate>
                    <asp:imagebutton id="btnView" runat="server">
                        CausesValidation="False" CommandName="MyCommand"
                        CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
                        ImageUrl="~/Select.gif" ToolTip="View" />
                </asp:imagebutton></itemtemplate>
            </asp:templatefield>
            <asp:boundfield datafield="A" headertext="A" sortexpression="A" />
            <asp:boundfield datafield="B" headertext="B" sortexpression="B" />
            <asp:boundfield datafield="C" headertext="C" sortexpression="C" />
        </columns>
    </asp:gridview>

GeneralRe: template works well PinmemberUrs Enzler4:33 6 Oct '08  
GeneralRe: template works well PinmemberUrs Enzler2:41 9 Oct '08  
GeneralMy fix PinmemberPartenon3:40 6 Aug '08  
GeneralThanks PinmemberH@is@here4:39 26 Jun '08  
GeneralRe: Thanks PinmemberUrs Enzler6:05 26 Jun '08  
GeneralGreat Post! Pinmemberrk113811:56 4 Apr '08  
GeneralRe: Great Post! PinmemberUrs Enzler4:53 20 Jun '08  
GeneralFound a better fix Pinmembersrone14:52 31 Mar '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120604.1 | Last Updated 10 Oct 2008
Article Copyright 2007 by Urs Enzler
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid