Thursday 29 December 2011

Dinamically add rows in gridview from another gridview

you need to add rows in gridview dynamically from database or controls or from another gridview.
This example shows, how to add rows dynamically in gridview.

We need Dataset, DataTable, DataColumn, DataRow to populate second gridview


Page.aspx.cs code

public partial class Sent : System.Web.UI.Page
{
DataSet ds=new DataSet();
DataTable dt=new DataTable();
DataColumn dc;
DataColumn dc1;

protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
dc = new DataColumn("Name", Type.GetType("System.String"));
dc1 = new DataColumn("Number", Type.GetType("System.String"));
dt.Columns.Add(dc);
dt.Columns.Add(dc1);
}
}

protected void btnapp_Click(object sender, EventArgs e)
{
try
{
dc = new DataColumn("Name", Type.GetType("System.String"));
dc1 = new DataColumn("Number", Type.GetType("System.String"));
dt.Columns.Add(dc);
dt.Columns.Add(dc1);
DataAccess da = new DataAccess();
DataRow dr;
if(GridView2.Rows.Count != 0)
{
foreach(GridViewRow row in GridView2.Rows)
{
dr = dt.NewRow();
dr["Name"]= row.Cells[0].Text ;
dr["Number"]= row.Cells[1].Text;
dt.Rows.Add(dr);
}
}
foreach(GridViewRow row in GridView1.Rows)
{
CheckBox ch = (CheckBox)row.FindControl("Edit");
if(ch.Checked)
{
dr = dt.NewRow();
dr["Name"]= row.Cells[1].Text + " " +row.Cells[2].Text;
dr["Number"]= row.Cells[5].Text;
dt.Rows.Add(dr);
}
}
ds.Tables.Clear();
ds.Tables.Add(dt);
ds.AcceptChanges();
GridView2.DataSource =ds.Tables[0];
GridView2.DataBind();
}
catch(SqlException ex)
{
}
} }

No comments:

Post a Comment