Ok so it appears in the .NET framework API docs that the CommandArgument property of the CommandEventArg class开发者_高级运维 is of type 'object' suggesting that I might assign to it something other than a string object yet I get an InvalidCastException using the code below:
[aspx code]
...
<asp:Button ID="Button1" runat="server" CommandArgument='<%# context %>' oncommand='reviewContext' </asp:Button>
...
[aspx.cs codebehind code]
...
public Enum Context { C1, C2, C3 }
public Context context { get { return Context.C1; } }
...
public void reviewContext (object sender, CommandEventArg e) {
if((Context) e.CommandArgument == Context.C1) { /*Do something in context of C1 */}
}
Why is it tabu to assign something other than a string to the CommandEventArg property?
Because it needs to render the item in the HTML, if it can't make it a string how can it render.
return Context.C1.ToString()
This will work fine.
You can use your enum, you just can't do it in the HTML side. The HTML side is specifically a string representation of the classes involved. You can, however, assign a function to this databinding event, and return the string representation of what is necessary, so
public Context context { get { return Context.C1; } }
becomes
public string context { get { return Context.C1.ToString(); } }
However, in order to use the enums once you're in reviewContext
you'll need to parse the enum out in order to make the comparison:
(Context)Enum.Parse(typeof(Context), "C1");
Note: You can still use the strings to make the comparison, but that defeats the point of the enum I think.
精彩评论