要实现GridView行编辑功能,可以按照以下步骤进行:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowEditing="GridView1_RowEditing">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:ButtonField ButtonType="Link" Text="Edit" CommandName="Edit" />
</Columns>
</asp:GridView>
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" />
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>' Visible='<%# Eval("ID").ToString() != editID %>'></asp:Label>
<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>' Visible='<%# Eval("ID").ToString() == editID %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Link" Text="Edit" CommandName="Edit" />
<asp:ButtonField ButtonType="Link" Text="Update" CommandName="Update" />
<asp:ButtonField ButtonType="Link" Text="Cancel" CommandName="Cancel" />
</Columns>
</asp:GridView>
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//获取编辑行的数据,并更新到数据库中
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView();
}
private void BindGridView()
{
GridView1.DataSource = //获取数据源
GridView1.DataBind();
}
通过以上步骤,就可以实现GridView行编辑功能。用户点击编辑按钮时,当前行的数据会显示在编辑控件中,用户可以修改数据并保存或取消编辑操作。