C#asp.net Gridview导航到gridview行中的url

时间:2017-07-24 09:07:37

标签: c# url gridview

我正在开发一个内部项目,我创建了一个连接到SQL表的GridView,如下所示:

GridView1

Example image of GridView1

我使用以下代码创建了视图内容按钮:

<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>

但这就是我现在陷入困境的地方。 我想点击查看内容按钮,然后导航到所选行上的网址。

URL来自SQL表,有一个字符串,所以我想,它需要先转换,但我可能是错的。

我开始将我的代码放在以下内容中:

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

2 个答案:

答案 0 :(得分:1)

GridView1_RowCommand的{​​{1}}事件中添加您的代码:

gridview

注意:不要忘记在GrindView中添加OnRowCommand事件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 } }

答案 1 :(得分:1)

            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

所以我做了改变。很遗憾,BoundField不包含NamingContainer的定义。

此外,GridView1.Rows[index].FindControl("URL") as BoundField由于以下错误而失败,无法通过引用转换将拳击'system.web.ui.control'转换为'system.web.ui.webcontrols.boundfield'转换,取消装箱转换或空类型转换。