Chris
Chris

Reputation: 371

Redirect to specific page when a gridview buttonfield is clicked

I have two fields in my gridview. One is a field with a date range and one of them is a buttonfield. I want to make it so that when a button is clicked, it will redirect them to a specific page with a formatted string similar to how it's done when a hyperlinkfield is clicked as such:

DataNavigateUrlFormatString="ProductInfo.aspx?ProductID={0}"

However, I don't want to use the other field's value(the date range). I want to use the primary key of the record which is "SundayOfWeek". The user wants a button rather than a hyperlink. Is there a way I can do the same thing with a button?

Upvotes: 0

Views: 9556

Answers (3)

Celtik
Celtik

Reputation: 347

Try using this type of column instead of a ButtonField:

<Columns>
   <asp:HyperLinkField 
     DataTextField="ProductName" 
     HeaderText="Product Name" 
     SortExpression="ProductName" 
     DataNavigateUrlFields="ProductID" 
     DataNavigateUrlFormatString="ProductInfo.aspx?ProductID={0}" />
</Columns>

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460068

If you don't want to use the date-range field, you should use another column as DataNavigateUrlField:

DataNavigateUrlField="KeyField"
DataTextField="DateField"
DataNavigateUrlFormatString="ProductInfo.aspx?ProductID={0}"

If you don't want to use a HyperLinkColumn, you should use a TemplateField and add a Button:

 <asp:TemplateColumn> 
      <input type="button" onclick="location.href='ProductInfo.aspx?ProductID=<%#Eval("KeyField")%>'" value='<%#Eval("DateField")%>'' />
 </asp:TemplateColumn> 

Upvotes: 0

Icarus
Icarus

Reputation: 63956

Sure, one of many ways is this:

 <columns>
      <asp:templatefield headertext="Button">
        <itemtemplate>
          <asp:Button id="btnRedirect"
            Text= "Click me"
            CommandArgument='<%#Eval("SundayOfWeek")%>'
            OnClick="DoRedirect"
            runat="server"/> 
        </itemtemplate>
      </asp:templatefield>
    </columns>


protected void DoRedirect(object sender, EventArgs e)
{
    Button theButton = sender as Button;
    Response.Redirect("Newpage.aspx?ID="+theButton.CommandArgument);
}

Upvotes: 0

Related Questions