How to create dynamic Gridview?


Many times we have the requirement where we have to create columns dynamically.
This article describes you about the dynamic loading of data using the DataTable as the datasource.

Details of the Grid

Let?s have a look at the code to understand better.

Create a gridview in the page,

Drag and drop the GridView on to the page
Or

Manually type GridView definition in the page.


public partial class _Default : System.Web.UI.Page

{

#region constants

const string NAME = “NAME”;

const string ID = “ID”;

#endregion

protected void Page_Load(object sender, EventArgs e)

{

loadDynamicGrid();

}

private void loadDynamicGrid()

{

#region Code for preparing the DataTable

//Create an instance of DataTable

DataTable dt = new DataTable();

//Create an ID column for adding to the Datatable

DataColumn dcol = new DataColumn(ID ,typeof(System.Int32));

dcol.AutoIncrement = true;

dt.Columns.Add(dcol);

//Create an ID column for adding to the Datatable

dcol = new DataColumn(NAME, typeof(System.String));

dt.Columns.Add(dcol);

//Now add data for dynamic columns

//As the first column is auto-increment, we do not have to add any thing.

//Let’s add some data to the second column.

for (int nIndex = 0; nIndex < 10; nIndex++)

{

//Create a new row

DataRow drow = dt.NewRow();

//Initialize the row data.

drow[NAME] = “Row-” + Convert.ToString((nIndex + 1));

//Add the row to the datatable.

dt.Rows.Add(drow);

}

#endregion

//Iterate through the columns of the datatable to set the data bound field dynamically.

foreach (DataColumn col in dt.Columns)

{

//Declare the bound field and allocate memory for the bound field.

BoundField bfield = new BoundField();

//Initalize the DataField value.

bfield.DataField = col.ColumnName;

//Initialize the HeaderText field value.

bfield.HeaderText = col.ColumnName;

//Add the newly created bound field to the GridView.

GrdDynamic.Columns.Add(bfield);

}

//Initialize the DataSource

GrdDynamic.DataSource = dt;

//Bind the datatable with the GridView.

GrdDynamic.DataBind();

}

}

Advertisements

One Response to How to create dynamic Gridview?

  1. Adelynn says:

    I don’t know if it’s just me or if perhaps everyone else experiencing issues with your blog.
    It appears like some of the written text on your posts are running off the
    screen. Can somebody else please comment and let me know if this is happening to them too?
    This could be a issue with my browser because I’ve had this happen previously. Thank you

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: