如何使用DataKey从网格视图重定向

时间:2011-11-24 12:04:32

标签: c# asp.net gridview datagrid databound

我想在单击一行时重定向网格视图,因此我有网格视图的OnRowCreated,我无法重定向到我想要的页面

<asp:GridView ID="Grid_Messagetable" runat="server" OnRowCreated="Grid_Messagetable_RowCreated" AllowPaging="False" SelectedIndex="0"
                 DataKeyNames="MsgID" ShowHeaderWhenEmpty="true"
                OnRowDataBound="MyGrid_RowDataBound" AutoGenerateColumns="False" AllowSorting="true"
                OnSorting="gridView_Sorting" Height="16px" Width="647px">     protected void Grid_Messagetable_RowCreated(object sender, GridViewRowEventArgs e)
    {
        e.Row.Attributes.Add("onClick", "this.style.background='#eeff00'");
    }

这里我尝试在单击一行时设置背景颜色并且它有效但是如何重定向页面,我必须使用msgID重定向到ResponseMetrci.aspx页面,就像我在下面做的那样。所以我在网址中传递了msgid,以便在响应度量页面中检索它。

Eval("MsgID", "ResponseMetric.aspx?MsgID={0}") %>'

我试过这个

e.Row.Attributes["onClick"] = "location.href=
 'ResponseMetric.aspx?MsgID=" + DataBinder.Eval(e.Row.DataItem, "MsgID") + "'";

但我收到错误

Uncaught ReferenceError: redirect is not defined
(anonymous function)Messages.aspx:774
onclick

2 个答案:

答案 0 :(得分:2)

简单修复,只需更改我已经实现的RowDataBound方法,即可包含以下代码段:

protected void MyGrid_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onClick"] = string.Format(
            "window.location = 'ResponseMetric.aspx?MsgID={0}';",
            DataBinder.Eval(e.Row.DataItem, "MsgID"));
    }
}

以下是Google的一个基本工作示例:

protected void grdTest_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onClick"] =
            "window.location = 'http://www.google.com/';";
    }
}

答案 1 :(得分:0)

如果需要,您可以打开新窗口并关闭现有窗口。试试这个e.Row.Attributes.Add(“onClick”,“javascript:window.open('ResponseMetric.aspx?MsgID =”+你的价值+“')”)。