Click here to Skip to main content
15,884,298 members
Articles / Web Development / ASP.NET

Dynamic Table in ASP.NET using C#

Rate me:
Please Sign up or sign in to vote.
4.77/5 (9 votes)
16 Mar 2011CPOL1 min read 114.5K   7   1
Dynamic Table in ASP.NET using C#

Dynamic table in the sense to create a data table dynamically and add rows one by one programmatically. After creating Data Table and adding rows, we can bind that data table to any data grid or grid view as a data source.

Why and Where We Need It?

Suppose we are developing a Shopping Cart application or creating a wish list or adding sub category and want to add database after adding category, at that time, we need any data source to hold it temporarily. In the above circumstances, we can use data table very effectively.

Here is the Working Code

I had created a Class file for creating a Data Table and Column, but you can use it as per your requirement.

DynamicTable.cs Class File

Here, we will create a table width name and Id two fields.

C#
public class DynamicTable 
{ 
       public DynamicTable() { } 
       public DataTable CreateDataSource() 
      { 
                    DataTable dt = new DataTable(); 
                    DataColumn identity = new DataColumn("ID", typeof(int)); 
                    dt.Columns.Add(identity); 
                    dt.Columns.Add("Name", typeof(string)); 
                    return dt; 
       } 
       //This is the AddRow method to add a new row in Table dt 
       public void AddRow(int id,string name, DataTable dt) 
      { 
                  dt.Rows.Add(new object[] { id,name,pname }); 
      } 
}

Here is our aspx page:

HTML
<body>
<form id="form1" runat="server">
<div>
<table style="width:50%;">
<tr>
<td>
Add Name<td>
<td>
<asp:TextBox ID="TextBox1" runat="server"><asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="Button1" runat="server" Text="Add Name"
onclick="Button1_Click" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:GridView ID="GridView1" 
runat="server" AutoGenerateColumns="false"
DataKeyNames="ID" EmptyDataText ="There are no data here yet!"
onrowcommand="GridView1_RowCommand"
onrowdatabound="GridView1_RowDataBound" 
onrowdeleting="GridView1_RowDeleting" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>NameHeaderTemplate>
<ItemTemplate>ItemTemplate>
<asp:TemplateField>
<asp:TemplateField HeaderText="Remove">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" CommandArgument=''
CommandName="Delete" runat="server">Removeasp:LinkButton>
<ItemTemplate>
<asp:TemplateField>
<Columns>
<asp:GridView>td>
</tr>
</table>
</div>
</form>
</body>

Here is the aspx.cs file:

When we add a new name to data table, this code will fire. Here, we are maintaining session for datacolumid and to hold that data table line has its own comment so you can understand it easily.

C#
protected void Button1_Click(object sender, EventArgs e)
{
         DynamicTable Dt = new DynamicTable();
         DataTable d = null;
         //If session is not there means first time addinf record.
         if (Session["dt"] == null)
         {
                 d = Dt.CreateDataSource();
                 Session["IDClm"] = 1;
          }
 //else we are converting session of datatable to data table and increment the column id by 1;
          else
         {
                 Session["IDClm"] = Convert.ToInt16(Session["IDClm"]) + 1;
                 d = (DataTable)Session["dt"];
          }
        
          //Assign both fields with data
          int ID = Convert.ToInt16(Session["IDClm"]);
          string name = TextBox1.Text;
          //call AddNew method and pass id,name and object of datatable
          Dt.AddRow(ID, name, d);
          //Again bind it with gridview
          GridView1.DataSource = d;
          GridView1.DataBind();
          //finally assign to session also.
          Session["dt"] = d;
 }

Whenever user wants to delete record from Data Table, then ask for confirmation "Are you sure?" Something like this. This code I implement in RowDataBound Event of the gridView1 as follows:

C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
       if (e.Row.RowType == DataControlRowType.DataRow)
      {
//We are checking if new row is adding then bind javascript function to ask
//confirmation from user for deletion record.
LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
l.Attributes.Add("onclick", "javascript:return " +
"confirm('Are you sure you want to delete this Name " +
DataBinder.Eval(e.Row.DataItem, "id") + "')");
       }
}
//This code for delete the record in RowCommand event

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
//We are deleting records from datatable
int ID = Convert.ToInt32(e.CommandArgument);
DataTable updt = (DataTable)Session["dt"];
int i = 0;
while (i <>)
{
if (Convert.ToInt16(updt.Rows[i]["ID"]) == ID)
updt.Rows[i].Delete();
i++;
 }

//After delete data from datatable accept the changes and then bind it to gridview again
updt.AcceptChanges();
GridView1.DataSource = updt;
GridView1.DataBind();
//And finally update the session with modified datatable;
 Session["dt"] = updt;
 }
}

//This code block for handling the Row Deleting event there are no lines of code
//inside this event but still it’s necessary otherwise it will generate error.

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
This article was originally posted at http://myvsdotnetstuff.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Working in Ahmedabad, Gujarat, India
India India

I am working as a Software Engineer in Ahmedabad, Gujrat, India.

I have 12+ Years of Experience in Microsoft Technology Like Asp.Net 4.0,
C#,MVC,EntityFramework, Javascript, Crystal Reports, JQuery etc.

Find out more on :




Comments and Discussions

 
GeneralMy vote of 3 Pin
hebsiboy10-Mar-12 21:32
hebsiboy10-Mar-12 21:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.