Monday, October 29, 2012

Dynamically add columns to GridView in asp.net using C#.net

Title:How to create dynamic columns in grid view in asp.net using c#.net

Description:
Up to now we have gone through the data binding concepts like bind data to drop down list in grid view and how to use the link button in grid view.Here i would like to explain how to do customized grid view using c#.net.t.For this the i have created a data table which has three columns and assign the list data to data table using iterations.The resultant grid view can see in the below image

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Add rows Dynamically to grdivew</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:gridview autogeneratecolumns="False" id="DynamicColAddGrid" runat="server">
</asp:gridview>
</div>
</form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _DynamicCol : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> li = new List<string>();
li.Add("Bhaskar");
li.Add("Siva");
li.Add("Ram");
li.Add("Venky");
li.Add("Hari");
li.Add("Aru");
li.Add("Srinu");
li.Add("anil");
li.Add("sri");
li.Add("john");
DataTable ddt = new DataTable();
DataRow darow;
DataColumn dc = new DataColumn("Id", typeof(string));
DataColumn dc1 = new DataColumn("Name", typeof(string));
DataColumn dc2 = new DataColumn("FullName", typeof(string));
ddt.Columns.Add(dc);
ddt.Columns.Add(dc1);
ddt.Columns.Add(dc2);
int ditem = 0;
while (ditem < 8)
{
darow = ddt.NewRow();
ddt.Rows.Add(darow);
ddt.Rows[ditem][dc] = ditem.ToString();
ddt.Rows[ditem][dc1] = li[ditem].ToString();
ddt.Rows[ditem][dc2] = li[ditem].ToString();
ditem++;
}    
DynamicColAddGrid.DataSource = ddt;
DynamicColAddGrid.DataBind();  
}
}
Result:

No comments:

Bel