Monday, May 14, 2012

Creating the Table dynamically and biding to the Grid view


In this article I am going to explain about how to create a table dynamically and how to add this to grid view.

What is dynamic table ?
Dynamic table is nothing but create a table dynamically and add rows and columns dynamically using c# programming.i.e. creating the table in the code behind is called Dynamic table.

How can we create the dynamic table?
To create the dynamic table we will use the “DataTable” class of the C#.net.For Adding new column we will use the “DataColumn” class and for adding new Row we will use the “DataRow” Class.

To create the Dynamic table letus create a new Aspx page with the following Code :


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Dynamic dtatTable creation</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDyndatatable" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>


Then add the following Name space to the code behind file :
using System.Data;

Then add the following code in the code behind .


protected void Page_Load(object sender, EventArgs e)
        {
            BindGvData();
        }

        private void BindGvData()
        {
            //Create a Datatable
            DataTable objDatatable = new DataTable();
            //Adding columns to the Data Table
            objDatatable.Columns.Add("Id", typeof(Int32));
            objDatatable.Columns.Add("StudentName", typeof(string));
            objDatatable.Columns.Add("Education", typeof(string));

            objDatatable = AddNewRow(1, "Prakash", "MCA", objDatatable);
            objDatatable = AddNewRow(2, "Pradeep", "MBA", objDatatable);
            objDatatable = AddNewRow(3, "Sathya", "BTECH", objDatatable);
            objDatatable = AddNewRow(4, "Sagar", "Degree", objDatatable);

            gvDyndatatable.DataSource = objDatatable;
            gvDyndatatable.DataBind();
        }

        public DataTable AddNewRow(int id, string name, string Education, DataTable objDatatable)
        {
            DataRow objDatatablerow = objDatatable.NewRow();
            objDatatablerow["Id"] = id;
            objDatatablerow["StudentName"] = name;
            objDatatablerow["Education"] = Education;
            objDatatable.Rows.Add(objDatatablerow);
            return objDatatable;

        }

Output:



No comments:

Post a Comment