2

GridViewにバインドされた を使用していList<Customer>ます。がいくつかのボタンによって起動されたときに、次のように からRowCommand現在の行のCustomerオブジェクトを取得できるようにしたいe.CommandArgument:

protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Customer customer = (Customer)e.CommandArgument;
    DoSomething(customer);
}

イベントが発生する前にCustomerオブジェクトを割り当てるにはどうすればよいですか?CommandArgument

4

1 に答える 1

2

I am not sure you can actually store a complex object in the CommandArgument as it seems to only take string or numeric values.

Something, which I have never really put into practice, is to convert your object into a Json string and use this as your command argument.

For example, using Newtonsoft.Json and a dummy object called FooBar

<asp:Button ID="btnOne" runat="server" 
CommandName="Click" 
CommandArgument='<%#Newtonsoft.Json.JsonConvert.SerializeObject((FooBar)Container.DataItem) %>' 
Text="Click" />

Then when you handle the GridView RowCommand click event, you can Deserialize the object from the CommandArgument

FooBar fooBar = Newtonsoft.Json.JsonConvert.DeserializeObject<FooBar>(e.CommandArgument.ToString());

Now this works, but whether it is the best solution, I am not sure.

于 2013-05-03T09:22:25.430 に答える