Reputation: 4696
I want to add hyperlinks to cells of an ASP.NET GridView control dynamically at run time, but am unclear as to the proper approach.
First I tried simply adding the link to the GridView:
HyperLink the_url = new HyperLink();
the_url.NavigateUrl = "http://www.stackoverflow.com";
the_url.Text = "Stack Overflow";
MyGridView.Rows[0].Cells[0].Controls.Add(the_url);
This compiled, but got a run time error because of course there were no rows.
Next, I tried binding a DataTable:
dt = new DataTable();
// Add columns to table
DataColumn col = new DataColumn();
col = new DataColumn("URL");
dt.Columns.Add(col);
col = new DataColumn("Title");
dt.Columns.Add(col);
// Add row to table
DataRow dr = dt.NewRow();
dr["URL"] = the_url;
dr["Title"] = "Stack Overflow";
dt.Rows.Add(dr);
// Bind table
MyGridView.DataSource = dt;
MyGridView.DataBind();
This creates the row, but instead of showing the link, it display plain text "System.Web.UI.WebControls.HyperLink".
What am I missing?
Upvotes: 0
Views: 4872
Reputation: 1161
Use RowDataBound
event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
HyperLink the_url = new HyperLink();
the_url.NavigateUrl = "http://www.stackoverflow.com";
the_url.Text = "Stack Overflow";
e.Row.Cells[0].Controls.Add(the_url);
}
Upvotes: 3