Below is the code snippet in C#.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//get data from programmatically created DataTable and bind to GridView
gvTable.DataSource = CreateTable();
gvTable.DataBind();
}
}
//Create DataTable programmatically
//In this example, there are three columns
//namely ID, WebsiteName and URL
private DataTable CreateTable()
{
//create datatable
DataTable table = new DataTable("Websites");
//add columns to the table
table.Columns.Add("ID", typeof(int));
table.Columns.Add("WebsiteName", typeof(string));
table.Columns.Add("URL", typeof(string));
//add as many rows as you want
AddNewRow(1, "dotnetspidor", "http://dotnetspidor.blogspot.com", table);
AddNewRow(1, "asp.net", "http://asp.net", table);
AddNewRow(1, "codeplex", "http://codeplex.com", table);
return table;
}
//Add new row to a table
private void AddNewRow(int id,string website, string url,DataTable table)
{
DataRow row = table.NewRow();
row["ID"] = id;
row["WebsiteName"] = website;
//get url from GetURL method
string link = GetURL(website, url);
row["URL"] = HttpUtility.HtmlDecode(link);
table.Rows.Add(row);
}
//create html anchor from website name and it's url
private string GetURL(string website, string url)
{
return "<a href=\""+url+"\">"+website+"</a>";
}
Here goes the design code for the GridView. Please note the property HtmlEncode="false" in the third BoundField. This prevents the GridView from rendering encoded html so we retain the html code from our DataTable column.
<asp:gridview autogeneratecolumns="false" id="gvTable" runat="server" width="500px">
<columns>
<asp:boundfield datafield="ID" headertext="ID">
<asp:boundfield datafield="WebsiteName" headertext="Website">
<asp:boundfield datafield="URL" headertext="URL" htmlencode="false">
</asp:boundfield></asp:boundfield></asp:boundfield></columns>
</asp:gridview>
The output looks like below.
![]() |
| Fig: Output of programmatically generated DataTable in a gridview - with clickable row |

Very nice one.
ReplyDeleteThank You.
Nice post.........
ReplyDeleteDot Net World