如何在ASP.NET GridView中为按钮/链接添加href

时间:2017-02-24 13:00:54

标签: c# asp.net gridview webforms

我有一个ASP.NET Web应用程序,可以处理来自其他站点的一些数据,并在gridview中显示信息。我不知道gridview将拥有多少行,也不知道有多少列。

在这个gridview中,我有一个模板字段,我用它来添加一个Checkbox。 使用我绑定到此gridview的DataTable添加其余列。现在的问题是,在10列之后,我有一个URL,我想将其显示为按钮或链接。在此链接之后,我有x列的列。

如何在具有动态行的GridView中添加静态列和动态列之间的URL?

我尝试在DataTable中编写href = link ..但它将其显示为文本。 我找到了一篇用HtmlDecode提出建议的文章,但为了实现这一点,我需要使用设置htmlencode = false的boundfields。或类似的东西。

有没有办法做到这一点?或者我应该只移动包含复选框的itemtemplate中的链接并尝试将其设置在那里?

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以使用 MatchGrid_RowDataBound 方法查看列并根据需要添加按钮。
以下是如何在RowDataBound上添加按钮的示例:

How do I programmatically add a button to a gridview and assign it to a specific code-behind function?

答案 1 :(得分:1)

您可以使用OnRowDataBound。它会将额外的单元格插入GridView。在将其绑定到GridView之前,您还可以在DataTable 中插入额外的列。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //header
    if (e.Row.RowType == DataControlRowType.Header)
    {
        //add 6 cells
        for (int i = 1; i <= 6; i++)
        {
            TableHeaderCell headerCell = new TableHeaderCell();

            if (i == 6)
            {
                headerCell.Text = "URL";
            }
            else
            {
                headerCell.Text = "Static " + i;
            }

            //add the new cell to the gridview
            e.Row.Cells.AddAt(i, headerCell);
        }
    }

    //normal row
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //cast the current row to a datarowview
        DataRowView row = e.Row.DataItem as DataRowView;

        //add 6 cells
        for (int i = 1; i <= 6; i++)
        {
            TableCell cell = new TableCell();

            if (i == 6)
            {
                cell.Text = string.Format("<a target=\"_blank\" href=\"{0}\">{0}</a>", row["myURL"]);
            }
            else
            {
                cell.Text = "Enter stuff here...";
            }

            //add the new cell to the gridview
            e.Row.Cells.AddAt(i, cell);
        }
    }
}