I have managed to do it.
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCreated = "OnRowCreated" OnRowEditing="OnRowEditing">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton Text="Update" runat="server" OnClick="OnUpdate" />
<asp:LinkButton Text="Cancel" runat="server" OnClick="OnCancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
using System.Data;
using System.Drawing;
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
ViewState["dt"] = dt;
this.BindGrid();
}
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
}
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (GridView1.EditIndex != -1 && e.Row.RowType == DataControlRowType.DataRow)
{
int index = 0;
foreach (TableCell cell in e.Row.Cells)
{
if(cell.Controls.Count > 0)
{
if (cell.Controls[0] is TextBox)
{
TextBox textBox = cell.Controls[0] as TextBox;
textBox.ID = "txt" + GridView1.HeaderRow.Cells[index].Text.Replace(" ", "");
RequiredFieldValidator vaidator = new RequiredFieldValidator
{
ControlToValidate = textBox.ID,
ForeColor = Color.Red,
ErrorMessage = "Required",
ValidationGroup = "Update"
};
cell.Controls.Add(vaidator);
}
else
{
LinkButton lnkUpdate = cell.Controls.OfType<LinkButton>().Where(lnk => lnk.Text == "Update").FirstOrDefault();
if (lnkUpdate != null)
{
lnkUpdate.ValidationGroup = "Update";
}
}
}
index++;
}
}
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
string name = (row.Cells[0].Controls[0] as TextBox).Text;
string country = (row.Cells[1].Controls[0] as TextBox).Text;
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[row.RowIndex]["Name"] = name;
dt.Rows[row.RowIndex]["Country"] = country;
ViewState["dt"] = dt;
GridView1.EditIndex = -1;
this.BindGrid();
}
protected void OnCancel(object sender, EventArgs e)
{
GridView1.EditIndex = -1;
this.BindGrid();
}
Screenshot
