c# - 使用 AutoGenerateColumns 将超链接绑定(bind)到 GridView

标签 c# asp.net gridview hyperlink datatable

我有一个数据表,其中包含在运行时动态生成的列。此 DataTable 绑定(bind)到 AutoGenerateColumns 设置为 true 的 GridView。我遇到了一个问题,因为 DataTable 中的一些数据是 HyperLink 对象,所以它没有显示表中的实际链接,而是显示“System.Web.UI.WebControls.HyperLink”。

通常,我只会在我的 GridView 中使用 HyperLinkField,但由于 GridView 的列是自动生成的,我不确定如何执行此操作。有什么想法吗?

最佳答案

您可以动态添加新列,您只需隐藏自动生成的列即可。

对于此解决方案,您可以将超链接存储在 2 列中 - 1 列用于链接,1 列用于您要显示的文本,或者如果您想要显示通用内容(如“单击此处”),您可以只存储链接 (例如“http://example.com.au/Default.aspx”)。

protected void GridView1_RowBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        //add new header
        TableCell tc = new TableCell();
        tc.Text = "Groovy Link";
        e.Row.Cells.Add(tc);
        //hide original column that has been autobound - skip column we just added
        for (int i = 0; i < e.Row.Cells.Count - 1; i++)
        {
            BoundField field = (BoundField)((DataControlFieldCell)e.Row.Cells[i]).ContainingField;
            if (field.DataField == "AutoGeneratedColumnName")
                field.Visible = false;
        }
    }
    else if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //create new tablecell
        TableCell tc = new TableCell();
        //do a check to see if the data is stored as a hyperlink in DB
        if (DataBinder.Eval(e.Row.DataItem, "AutoGeneratedColumnName").ToString().StartsWith("<a") == true)
        {
            //create hyperlink
            HyperLink hyp = new HyperLink();
            hyp.NavigateUrl = DataBinder.Eval(e.Row.DataItem, "AutoGeneratedColumnName").ToString();
            hyp.Text = "click here";
            tc.Controls.Add(hyp);
        }
        else
        {
            //just text
            tc.Text = DataBinder.Eval(e.Row.DataItem, "AutoGeneratedColumnName").ToString()
        }
        //add tablecell to row
        e.Row.Cells.Add(tc);
        //hide original column that has been autobound
        for (int i = 0; i < e.Row.Cells.Count - 1; i++)
        {
            BoundField field = (BoundField)((DataControlFieldCell)e.Row.Cells[i]).ContainingField;
            if (field.DataField == "AutoGeneratedColumnName")
                field.Visible = false;
        }
    }
}

关于c# - 使用 AutoGenerateColumns 将超链接绑定(bind)到 GridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4717307/

相关文章:

android - ViewGroup 在dispatchDragEvent 中抛出NullPointerException

c# - 尽管隐式 null 检查,ReSharper 仍对可能的 System.NullReferenceException 发出警告

asp.net - ASP :MenuItem/CSS

asp.net - 显示多个新窗口

asp.net - NodaTime 转换(第 2 部分)。如何?

asp.net - ASP.NET 中的 jQuery session

javascript - 使用 ESC 和 JavaScript Gridview 退出编辑模式

c# - 将类的列表传递给方法,方法中使用抽象基类的列表作为参数

c# - 在没有 HBM 文件的情况下设置 NHibernate/LINQ 的最快和最简单的方法

c# - Nhibernate ArgumentNullException 未处理 值不能为 null 参数名称 : stream