hi,you can add the row with text box dynamically on runtime with the click of button using this codesuppose that u have one grid view with three column and one button like that:
1. rownumber
2. first name
3. middle name
4. last name
on page load event.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetdefaultRow ();
// set the default gridview
}
}
private void SetdefaultRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("first name", typeof(string)));
dt.Columns.Add(new DataColumn("middle name", typeof(string)));
dt.Columns.Add(new DataColumn("last name", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["first name"] = string.Empty;
dr["middle name"] = string.Empty;
dr["last name"] = string.Empty;
dt.Rows.Add(dr);
//dr = dt.NewRow();
//Store the DataTable in ViewStateViewState["Table"] = dt;
Gridviewemp.DataSource = dt;
Gridviewemp.DataBind();
}
on button click:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRow();
// add new row with three textbox in gridview
}
private void AddNewRow()
{
int rowIndex =0;
if (ViewState["Table"] != null)
{
DataTable dtTable = (DataTable)ViewState["Table"];
DataRow drCurrentRow = null;
if (dtTable.Rows.Count > 0)
{
for (int i = 1; i <= dtTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
drCurrentRow["first name"] = box1.Text;
drCurrentRow["middle name"] = box2.Text;
drCurrentRow["last name"] = box3.Text;
rowIndex++;
}
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState
ViewState["Table"] = dtTable;
//Rebind the Grid with the current data
Gridviewemp.DataSource = dtTable;
Gridviewemp.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
}
Thanks and Regards
Varun Bansal
Assistant Programmer
NIC, Jaipur
No comments:
Post a Comment