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();
}
}

ご要望に応じて適宜な手法を選択し、データソースや実際の状況に合わせて適宜修正を加えてください。

bannerAds