我有一个GridView,其中包含一个模板字段内的链接按钮。代码如下所示:
<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" />
代码隐藏在下面:
protected void gv1_RowCommand(object sender, GridViewCommandEventArgs e)
{
gv1.EditIndex = 1;
}
单击链接按钮时,我将GridView编辑索引设置为1以使行可编辑。
现在我要保存更新的行。单击网页上的另一个按钮,我想保存更新的更改并将行编辑模式更改为不可编辑模式。
答案 0 :(得分:1)
执行此操作的最佳方法是使用特定事件,这样:
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();
}
要保存使用事件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();
}
请记住在gridview标记中声明事件。