要實現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行編輯功能。用戶點擊編輯按鈕時,當前行的數據會顯示在編輯控件中,用戶可以修改數據并保存或取消編輯操作。