Friday, November 14, 2008

Dynamic Table in Asp.Net using C#

Dynamic 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 we need it?

Suppose when ever 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 DataTable 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 Nametd>

<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 datatable this code will fire. Here we are maintaing session for datacolumid and to hold that datatable line has it’s 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;

}

When ever user want to delete record from Data Table then ask for confirmation that Are you sure? Some thing like this. This code I impletment 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 RowDeleteing 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){}

0 comments:

Template by - Abdul Munir | Daya Earth Blogger Template