溫馨提示×

gridview傳值無法修改如何解決

小億
107
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