我有一个DataTable,其中包含在运行时动态生成的列。此DataTable绑定到将AutoGenerateColumns设置为true的GridView。我遇到了这个问题,因为DataTable中的一些数据是HyperLink对象,因此它不显示表中的实际链接,而是显示“System.Web.UI.WebControls.HyperLink”。
通常,我只会在GridView中使用HyperLinkField,但由于GridView的列是自动生成的,我不知道如何做到这一点。有什么想法吗?
答案 0 :(得分:2)
您可以动态添加新列,您也只需要隐藏自动生成的列。
对于此解决方案,您可以将超链接存储在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;
}
}
}