Dynamically Create Different Controls on Grid view as a Single Column
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count ; i++)
{
TextBox tname = (TextBox)Gridview1.Rows[rowIndex].Cells[0].FindControl("txtName");
DropDownList sex = (DropDownList)Gridview1.Rows[rowIndex].Cells[0].FindControl("cboSex");
TextBox dob = (TextBox)Gridview1.Rows[rowIndex].Cells[0].FindControl("txtDob");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["Name"] = tname.Text;
drCurrentRow["Sex"] = sex.SelectedItem.Text;
drCurrentRow["Dob"] = dob.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 1; i < dt.Rows.Count; i++)
{
TextBox tname = (TextBox)Gridview1.Rows[rowIndex].Cells[0].FindControl("txtName");
DropDownList sex = (DropDownList)Gridview1.Rows[rowIndex].Cells[0].FindControl("cboSex");
TextBox dob = (TextBox)Gridview1.Rows[rowIndex].Cells[0].FindControl("txtdob");
tname.Text = dt.Rows[i]["Name"].ToString();
sex.Text = dt.Rows[i]["Sex"].ToString();
dob.Text = dt.Rows[i]["Dob"].ToString();
rowIndex++;
}
}
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Sex", typeof(string)));
dt.Columns.Add(new DataColumn("Dob", typeof(string)));
dr = dt.NewRow();
dr["Name"] = string.Empty;
dr["Sex"] = string.Empty;
dr["Dob"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
}