温馨提示×

gridview传值无法修改如何解决

小亿
106
2023-10-16 14:54:46
栏目: 编程语言

要在GridView中传递值并进行修改,您可以使用模板列或命令列。

如果您使用模板列,请确保在模板列中使用控件(如TextBox、DropDownList等)来显示和修改值,并在GridView的RowUpdating事件中处理更新操作。

示例代码如下:

<asp:GridView ID="GridView1" runat="server" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:Label ID="lblValue" runat="server" Text='<%# Eval("Value") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtValue" runat="server" Text='<%# Eval("Value") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>

在GridView的RowUpdating事件中,可以通过GridView的Rows属性获取修改后的值,并更新到数据源中。

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
TextBox txtValue = (TextBox)row.FindControl("txtValue");
string newValue = txtValue.Text;
// 将newValue更新到数据源中
GridView1.EditIndex = -1;
// 重新绑定GridView
BindGridView();
}

如果您使用命令列,可以在GridView的RowCommand事件中处理编辑命令,并在事件中获取修改后的值并更新到数据源中。

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridView1.EditIndex = rowIndex;
// 重新绑定GridView
BindGridView();
}
else if (e.CommandName == "Update")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[rowIndex];
TextBox txtValue = (TextBox)row.FindControl("txtValue");
string newValue = txtValue.Text;
// 将newValue更新到数据源中
GridView1.EditIndex = -1;
// 重新绑定GridView
BindGridView();
}
}

请根据您的需求选择适合您情况的方法,并根据您的数据源和实际情况进行相应的修改。

0