使用gridview实现编辑、更新、取消功能和删除功能
前台代码:
<asp:GridView ID="userInfoGrid" runat="server" AutoGenerateColumns="False" OnRowEditing="userInfoGrid_RowEditing" OnRowCancelingEdit="userInfoGrid_RowCancelingEdit" OnRowUpdating="userInfoGrid_RowUpdating" OnRowCommand="userInfoGrid_RowCommand">
<Columns>
<asp:BoundField DataField="userid" HeaderText="用户编号" ReadOnly="True" />
<asp:BoundField DataField="username" HeaderText="姓名" ReadOnly="True" />
<asp:BoundField DataField="userpassword" HeaderText="密码" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDel" runat="server" Text="删除" CommandName="Del" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" /> //实现编辑、更新、取消
</Columns>
</asp:GridView>
后台代码:
protected void userInfoGridBind()
{
DataTable dt = webtestBll.getAll();
userInfoGrid.DataSource = dt;
userInfoGrid.DataBind();
}
protected void userInfoGrid_RowEditing(object sender, GridViewEditEventArgs e)
{ //编辑
userInfoGrid.EditIndex = e.NewEditIndex;
userInfoGridBind();
}
protected void userInfoGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{ //取消
userInfoGrid.EditIndex = -1;
userInfoGridBind();
}
protected void userInfoGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{ //更新
string name = userInfoGrid.Rows[e.RowIndex].Cells[1].Text.ToString();
string password = ((TextBox)(userInfoGrid.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString();
webtestBll.Update(name, password);
userInfoGrid.EditIndex = -1;
userInfoGridBind();
}
protected void userInfoGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Del")
{//删除功能
Button btn = (Button)e.CommandSource;
GridViewRow row = (GridViewRow)btn.Parent.Parent;
string name = row.Cells[1].Text;
webtestBll.deleteByName(name);
userInfoGridBind();
}
}