Reputation: 14159
I have a GridView which contains a Link Button inside a Template Field. The code is shown below:
<asp:GridView ID="gv1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" onrowediting="gv1_RowEditing"
onrowcommand="gv1_RowCommand">
<Columns>
<asp:BoundField DataField="inDetailsId" HeaderText="inDetailsId"
SortExpression="inDetailsId" />
<asp:BoundField DataField="inUserId" HeaderText="inUserId"
SortExpression="inUserId" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnk1" runat="server" Text='<%# Eval("attDate")%>' CommandName="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="attstatus" HeaderText="attstatus"
SortExpression="attstatus" />
<asp:BoundField DataField="inAttendanceStatusId"
HeaderText="inAttendanceStatusId" SortExpression="inAttendanceStatusId" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:LearnConnectionString %>"
SelectCommand="SELECT * FROM [attendance]"></asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Text="Button" />
The code-behind is below:
protected void gv1_RowCommand(object sender, GridViewCommandEventArgs e)
{
gv1.EditIndex = 1;
}
On clicking the Link Button, I am setting GridView Edit Index to 1 to make the row editable.
Now I want to save the updated row. On Click of another button on the Web Page, I want to save the updated changes and change the row edit mode to non-editable mode.
Upvotes: 0
Views: 7156
Reputation: 143
The best way to do this is using the specifics events, this way:
protected void gridview1_RowEditing(object sender, GridViewEditEventArgs e)
{
gridview1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void gridview1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridview1.EditIndex = -1;
BindGrid();
}
To save use the event RowUpdating:
protected void gridview1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gridview1.Rows[e.RowIndex];
int id = Convert.ToInt32(gridview1.DataKeys[e.RowIndex].Value);
string name = ((DropDownList)(row.Cells[2].Controls[1])).SelectedValue;
//call save method of your business layer
gridview1.EditIndex = -1;
BindGrid();
}
Remember to declare the event in the gridview markup.
Upvotes: 1