Saturday, December 26, 2009

Adding the Row in Gridview

Adding The New Row in GridView by Using TextBox Values

Default3.aspx HTML Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>





Untitled Page




CellPadding="4" ForeColor="#333333" GridLines="None" OnPageIndexChanging ="Page" >




<%----%>
<%# ((GridViewRow)Container).RowIndex + 1%>





















style="top: 73px; left: 357px; position: absolute; height: 22px; width: 128px; margin-bottom: 1px">
style="top: 110px; left: 359px; position: absolute; height: 22px; width: 128px; margin-bottom: 1px">
style="top: 157px; left: 454px; position: absolute; width: 84px; right: 459px"
Text="Button" />





Code Behind Course Code Default3.aspx.cs Code


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Default3 : System.Web.UI.Page
{ DataTable dt1 = new DataTable();
DataRow dr = null;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["CurrentTable"] != null)
{
dt1=SetPreviousData();
dr = dt1.NewRow();
dr["ID"] = TextBox1.Text;
dr["Name"] = TextBox2.Text;
dt1.Rows.Add(dr);
GridView1.DataSource = dt1;
GridView1.DataBind();
}
else
{

GridView1.DataSource = GetTable();
GridView1.DataBind();

}


}

public DataTable GetTable()
{
DataTable Dt = new DataTable();
DataRow dr = null;

Dt.Columns.Add("S.No", typeof(Int32));
Dt.Columns.Add("ID", typeof(Int32 ));
Dt.Columns.Add("Name", typeof(string));
dr = Dt.NewRow();
dr["S.No"] = 1;
dr["ID"] = TextBox1.Text;
dr["Name"] = TextBox2.Text;
Dt.Rows.Add(dr);
ViewState["CurrentTable"] = Dt;
return Dt;
}

public DataTable SetPreviousData()
{
DataTable CurrentTable = new DataTable();
int rowIndex = 0;

if (ViewState["CurrentTable"] != null)
{
CurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow dr = null;

if (CurrentTable.Rows.Count > 0)
{
CurrentTable.Clear();

for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{

Label box1 = (Label)GridView1.Rows[rowIndex].Cells[1].FindControl("lblID");
Label box2 = (Label)GridView1.Rows[rowIndex].Cells[2].FindControl("lblName");
dr = CurrentTable.NewRow();
dr["S.No"] = i + 1;
dr["ID"] = box1.Text;
dr["Name"] = box2.Text;
rowIndex = i + 1;
CurrentTable.Rows.Add(dr);
}

ViewState["CurrentTable"]=CurrentTable;



}



}
return CurrentTable;




}
protected void Page(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
}
}