Jake Gaston
Jake Gaston

Reputation: 211

asp.net c# gridview buttons

I'm having trouble getting a gridview's button column to do anything. I'm using a DirectoryInfo object to get the details of a file. I put the filename and the date created into the gridview columns. The third column is a button column. I have set the datakeys(Name, CreationTime), named the button column's commandName to "sendcommand". I want to send the filename to another page. I have this code for the RowCommand event:

protected void gvFiles_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{

    if (e.CommandName == "sendcommand")
    {

        int index = Convert.ToInt32(e.CommandArgument);

        string fileID = ((GridView)sender).DataKeys[index]["Name"].ToString();
        Response.Redirect("irMain.aspx?@filename=" + fileID); 
    }
}

Nothing happens, except for a postback I think. How do I do this?

<asp:GridView ID="gvFiles" runat="server" Font-Name="Verdana" Font-Names="Verdana" 
        Width="401px" AutoGenerateColumns="False" BackColor="White" 
        BorderColor="Black" BorderStyle="Ridge" BorderWidth="2px" 
        DataKeyNames="Name,CreationTime" 
        >
        <Columns>
            <asp:HyperLinkField AccessibleHeaderText="File Name" 
                DataNavigateUrlFields="Name" DataNavigateUrlFormatString="~\Assets\reports\{0}" 
                DataTextField="Name" HeaderText="File Name" >

                <HeaderStyle BackColor="#0033CC" ForeColor="White" />
            </asp:HyperLinkField>
            <asp:BoundField AccessibleHeaderText="Date" DataField="CreationTime" 
                DataFormatString="{0:d}" HeaderText="Date">
                <HeaderStyle BackColor="Blue" ForeColor="White" />
            </asp:BoundField>

            <asp:ButtonField ButtonType="Button" Text="DO Stuff" CommandName="sendcommand" 
                HeaderText="WHAT?!" />

        </Columns>

        <AlternatingRowStyle BackColor="#6699FF" />

    </asp:GridView>

Upvotes: 1

Views: 4830

Answers (1)

Norm MacLennan
Norm MacLennan

Reputation: 451

You have to add the OnRowCommand attribute to your GridView in the ASPX, otherwise the GridView doesn't know what method to call when you execute a command on it.

AFAIK this is an entirely optional attribute and isn't generated via the designer so you have to add it manually when you want to use it.

Upvotes: 3

Related Questions