Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Dynamic Table in Asp.Net using C#

, 16 Mar 2011
Rate this:
Please Sign up or sign in to vote.
CodeProjectDynamic Table in Asp.Net using C#What is Dynamic Table?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

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 whenever we are developing Shopping Cart application or Creating wish list or adding sub category and want to add database after adding category that time we need any data source to hold it temporarily. In above circumstances we can use data table very effectively.

Here is the working code

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

DynamicTable.cs Class File

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

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 our aspx page is there

<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 add 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 easily.

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 increament 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 want to delete record from Data Table then ask for confirmation that Are you sure? Something like this. This code I implement in RowDataBound Event of the gridView1 as follow

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 deleteing 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 is 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)
{


}

License

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

Share

About the Author

Tarun Dudhatra
Software Developer Working in Ahmedabad, Gujarat, India
India India

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

I have 6+ Years of Experience in Microsoft Technology Like Asp.Net 2.0,Asp.Net 3.0,Asp.Net 4.0,
C#, Javascript, Crystal Reports, JQuery etc.

Find out more on :

Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 3 Pinmemberhebsiboy10-Mar-12 21:32 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140905.1 | Last Updated 16 Mar 2011
Article Copyright 2011 by Tarun Dudhatra
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid