【问题标题】:Trying to add hyperlink in GridView cell creates text尝试在 GridView 单元格中添加超链接会创建文本
【发布时间】:2014-04-22 16:51:30
【问题描述】:

我想在运行时动态地将超链接添加到 ASP.NET GridView 控件的单元格,但不清楚正确的方法。

首先我尝试简单地将链接添加到 GridView:

HyperLink the_url = new HyperLink();
the_url.NavigateUrl = "http://www.stackoverflow.com";
the_url.Text = "Stack Overflow";
MyGridView.Rows[0].Cells[0].Controls.Add(the_url);

这已编译,但由于当然没有行而出现运行时错误。

接下来,我尝试绑定一个DataTable:

dt = new DataTable();

// Add columns to table
DataColumn col = new DataColumn();
col = new DataColumn("URL");
dt.Columns.Add(col);
col = new DataColumn("Title");
dt.Columns.Add(col);

// Add row to table
DataRow dr = dt.NewRow();
dr["URL"] = the_url;
dr["Title"] = "Stack Overflow";
dt.Rows.Add(dr);

// Bind table
MyGridView.DataSource = dt;
MyGridView.DataBind();

这会创建行,但不是显示链接,而是显示纯文本“System.Web.UI.WebControls.HyperLink”。

我错过了什么?

【问题讨论】:

    标签: asp.net gridview hyperlink


    【解决方案1】:

    使用RowDataBound事件:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        HyperLink the_url = new HyperLink();
        the_url.NavigateUrl = "http://www.stackoverflow.com";
        the_url.Text = "Stack Overflow";
    
        e.Row.Cells[0].Controls.Add(the_url);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-10
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 2014-05-13
      相关资源
      最近更新 更多