【问题标题】:ASP.NET Add Hyperlink for whole row of Datatable/GridviewASP.NET 为整行 Datatable/Gridview 添加超链接
【发布时间】:2019-01-28 01:28:16
【问题描述】:

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

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)

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

【问题讨论】:

  • 在 Google 上搜索 Gridview Master / Details。
  • 没有帮助,这就是我问的原因
  • 不是将整行作为链接,您通常会将本示例中的描述字段作为链接。当您在代码而不是标记中创建这些时,它会变得更加混乱。还是可以的。
  • 所以,如果我理解正确,它是可行的,但只能使用更复杂但没有真正意义的方法?

标签: c# asp.net gridview datatable hyperlink


【解决方案1】:

您不能直接将链接添加到整行,但您可以使用属性和一些 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>

【讨论】:

  • 很抱歉,很晚才回复!非常感谢,这正是我寻找的那种解决方案!
  • 顺便说一句:是否可以在没有此事件的情况下以不同的方式将这些属性添加到行中?
  • 仅当您将 url 放入某些(隐藏的)字体结束元素中,例如 div 或 span 并且还使用 jquery 将其作为 data-url 添加到行中。
  • 好的,但在这种情况下,我认为我已经找到了正确的解决方案。再次感谢!
猜你喜欢
  • 2014-05-13
  • 2014-02-10
  • 2016-03-15
  • 2010-12-23
  • 2012-10-28
  • 2011-12-05
  • 1970-01-01
  • 2012-02-10
  • 1970-01-01
相关资源
最近更新 更多