C# asp.net Gridview navigate to url in gridview row

I'm currently working on an in house project, I've created a GridView connected to a SQL table which looks like this:

GridView1

Example image of GridView1

I created the view content buttons using the following code:

<Columns>
    <asp:ButtonField ButtonType="Button" Text="View Content" CommandName="Select" />
    <asp:BoundField DataField="ContentID" HeaderText="ContentID" InsertVisible="False" ReadOnly="True" SortExpression="ContentID" />
    <asp:BoundField DataField="Code" HeaderText="Code" SortExpression="Code" />
    <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
    <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
    <asp:BoundField DataField="URL" HeaderText="URL" Visible="true" SortExpression="URL" />                
</Columns>

But this is where I am now stuck. I would like to click on the view content button and have it navigate to the URL on the selected row.

The URL comes from the SQL Table and there is a string so I'd imagine, it would need to be converted first but I could be wrong.

I started to put my code in the following:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewCommandEventArgs x = (GridViewCommandEventArgs)e;
    if (x.CommandName == "Select")
    {
        GridViewRow row = GridView1.SelectedRow;
    }
}

Upvotes: 2

Views: 1110

Answers (2)

            GridViewRow row = (GridViewRow)(((BoundField)e.CommandSource).NamingContainer);
            int index = row.RowIndex;

            string url = (GridView1.Rows[index].FindControl("URL") as BoundField).Text;
            Response.Redirect(url); // url can be from your sql table

So i made the change. Unfortunately, BoundField does not contain a definition for NamingContainer.

Also, GridView1.Rows[index].FindControl("URL") as BoundField fails due to the following error, cannot convert type 'system.web.ui.control' to 'system.web.ui.webcontrols.boundfield' via a reference conversion, boxing conversion, unboxing conversion or null type conversion.

Upvotes: 1

user1773603
user1773603

Reputation:

Add your code in GridView1_RowCommand event of gridview:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
       if (e.CommandName == "Select")
        {
            GridViewRow row = (GridViewRow)(((BoundField)e.CommandSource).NamingContainer);
            int index = row.RowIndex;

            string url = (GridView1.Rows[index].FindControl("URL") as BoundField).Text;
            Response.Redirect(url); // url can be from your sql table

        }    
}

Note: Don't forget to add OnRowCommand event in GrindView <asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" >

Upvotes: 1

Related Questions