It is recommended to do this in javascript. Javascript is far more better performance as the task is carried out at client browser.
However, if you still want to do it at server side, below will give you an idea:
ASP.NET page code:
<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" xmlns:asp="#unknown">
<columns>
<asp:boundfield datafield="name" headertext="Name" />
<asp:boundfield datafield="tel" headertext="Tel" />
</columns>
</asp:gridview>
<br />
<asp:button id="Button_Edit" runat="server" onclick="Button_Edit_Click" xmlns:asp="#unknown">
Text="Edit" /></asp:button>
C# Code behind:
public partial class WebForm1 : System.Web.UI.Page
{
System.Data.DataTable dt
{
get
{
return (System.Data.DataTable)ViewState["dt"];
}
set
{
ViewState["dt"] = value;
}
}
bool isEditMode
{
get
{
if (ViewState["isEditMode"] == null)
return false;
return (bool)ViewState["isEditMode"];
}
set
{
ViewState["isEditMode"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dt = new System.Data.DataTable();
dt.Columns.Add("name");
dt.Columns.Add("tel");
dt.Rows.Add("Thomas", "1111");
dt.Rows.Add("Jessie", "2222");
dt.Rows.Add("Parker", "3333");
BindData();
isEditMode = false;
}
if (isEditMode)
AddTextBox();
}
void BindData()
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
void AddTextBox()
{
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
GridView1.Rows[i].Cells[j].Controls.Add(new TextBox());
}
}
}
void LoadDataIntoTextbox()
{
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
((TextBox)GridView1.Rows[i].Cells[j].Controls[0]).Text = dt.Rows[i][j] + "";
}
}
}
void SaveData()
{
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
dt.Rows[i][j] = ((TextBox)GridView1.Rows[i].Cells[j].Controls[0]).Text;
}
}
BindData();
}
protected void Button_Edit_Click(object sender, EventArgs e)
{
isEditMode = !isEditMode;
if (isEditMode)
{
Button_Edit.Text = "Save";
AddTextBox();
LoadDataIntoTextbox();
}
else
{
Button_Edit.Text = "Edit";
SaveData();
}
}
}