如何使用.NET CommandArgument作为非字符串对象?

时间:2010-12-08 19:23:56

标签: c# .net events types

好的,所以它出现在.NET framework API docs中,CommandEventArg类的CommandArgument属性是'object'类型,这表明我可能会为它分配一个字符串对象以外的东西但是我使用下面的代码得到一个InvalidCastException :

[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 */}
}

为什么禁止将其他字符串分配给CommandEventArg属性?

2 个答案:

答案 0 :(得分:2)

因为它需要在HTML中呈现项目,如果它不能使它成为字符串,它怎么能呈现。

return Context.C1.ToString()

这样可以正常工作。

答案 1 :(得分:1)

你可以使用你的枚举,你不能在HTML方面做到这一点。 HTML方面特别是涉及的类的字符串表示。但是,您可以为此数据绑定事件分配一个函数,并返回必要的字符串表示,所以

public Context context { get { return Context.C1; } }

变为

public string context { get { return Context.C1.ToString(); } }

但是,为了在reviewContext中使用枚举,您需要解析枚举以进行比较:

(Context)Enum.Parse(typeof(Context), "C1");

注意:您仍然可以使用字符串进行比较,但这会使我认为的枚举点失败。