我有一个DataTable,它包含在运行时动态生成的列。此DataTable绑定到AutoGenerateColumns设置为true的GridView。我遇到了一个问题,因为DataTable中的一些数据是HyperLink对象,所以它显示的不是表中的实际链接,而是"System.Web.UI.WebControls.HyperLink“。
通常,我只会在GridView中使用HyperLinkField,但由于GridView的列是自动生成的,我不确定该如何做。有什么想法吗?
发布于 2011-01-19 09:30:25
您可以动态添加新列,您只需隐藏自动生成的列即可。
对于此解决方案,您可以将超链接存储在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;
}
}
}https://stackoverflow.com/questions/4717307
复制相似问题