首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用AutoGenerateColumns将HyperLinks绑定到GridView

使用AutoGenerateColumns将HyperLinks绑定到GridView
EN

Stack Overflow用户
提问于 2011-01-18 04:03:43
回答 1查看 4.7K关注 0票数 2

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-01-19 09:30:25

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

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

代码语言:javascript
复制
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;
        }
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4717307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档