ASP.NET 为 Datatable/Gridview 的整行添加超链接

ASP.NET Add Hyperlink for whole row of Datatable/Gridview

我正在生成一个包含一些数据的数据表,并将其用作将添加到 ASP.NET-网页的 GridView 的数据源。

GridView gvItems = new GridView();
DataTable dtItems = new DataTable();

dtItems.Columns.Add("name");
dtItems.Columns.Add("description");
dtItems.Columns.Add("count");

foreach(var item in items)
{
    string name = item.name;
    string description = item.description;
    string count = item.count.ToString();
    string link = "~/Views/Items.aspx?item=" + item.name;
    string linkName = item.name;

    dtItems.Rows.Add(name, description, count)
}

gvItems.DataSource = dtItems;
gvItems.DataBind();

PlaceHolder.Controls.Add(gvItems)

是否可以为添加的每一行生成一个超链接? 如果有人单击行内的某处,我希望打开项目的详细页面。

您不能直接将 link 添加到整行,但可以使用属性和一些 jQuery 来完成。为此,您需要 RowDataBound 事件。但是由于您正在动态创建 GridView,因此您需要使用代码添加它。

gvItems.RowDataBound += GvItems_RowDataBound;
gvItems.DataSource = dtItems;
gvItems.DataBind();

然后是 RowDataBound 方法本身。

private void GvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the row is a datarow
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //cast the row back to a datarowview
        DataRowView row = e.Row.DataItem as DataRowView;

        //add the url as an attribute to the row
        e.Row.Attributes.Add("data-url", row["link"].ToString());

        //give the row a class to the jquery click event can be bound to it
        e.Row.Attributes.Add("class", "ClickableRow");
    }
}

然后使用一些前端代码来处理点击。

<script type="text/javascript">
    $(document).ready(function () {
        $(".ClickableRow").click(function () {
            location.href = $(this).data("url");
        });
    });
</script>