温馨提示×

请教一个gridview实现某列可编辑的功能

小云
104
2023-08-07 12:36:18
栏目: 编程语言

要实现GridView某列可编辑的功能,可以使用TemplateField和EditItemTemplate来定义可编辑的列。下面是一个简单的示例:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>

在上面的示例中,Name列是一个普通的绑定列,而Age列是一个可编辑的列。在ItemTemplate中,使用Label控件显示Age的值,在EditItemTemplate中,使用TextBox控件来编辑Age的值。

同时,还使用了CommandField来显示编辑按钮,点击编辑按钮时,GridView进入编辑模式,可编辑的列会显示为TextBox控件,从而允许用户编辑数据。

请注意,要在GridView的编辑模式下提交修改后的数据,还需要处理GridView的RowUpdating事件,并更新对应的数据源。

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
TextBox txtAge = (TextBox)row.FindControl("txtAge");
string newAge = txtAge.Text;
// 根据行索引和列名更新数据源中的对应值
GridView1.EditIndex = -1;
// 重新绑定数据源
}

以上是一个简单的示例,你可以根据实际需求进行修改和扩展。

0