代码之家  ›  专栏  ›  技术社区  ›  BrunoLM

如何在ascx上设置控件的int属性?

  •  7
  • BrunoLM  · 技术社区  · 14 年前

    我有一个包含

    <my:Foo ID="Bar" runat="server" Value='' />
    

    我想设置 Value 具有 textbox1.Text 但是 价值 是一个IT32。我在找这样的东西:

    <my:Foo ID="Bar" runat="server" Value='<%= Int32.Parse(textbox1.Text) %>' />
    

    但我得到

    Parser Error Message: Cannot create an object of type 'System.Int32' from its string representation '<%= Int32.Parse(textbox1.Text) %>' for the 'Value' property.
    

    在ascx文件中是否有这样的方法?是否必须为此属性实现类型转换器?

    2 回复  |  直到 14 年前
        1
  •  7
  •   Oded    14 年前

    我不明白为什么你不能简单地使用文字而不是字符串表示:

    <my:Foo ID="Bar" runat="server" Value="58" />
    

    如果要动态设置此值,则需要在代码隐藏或代码块内(例如在页面加载事件句柄中)执行此操作,因为不能使用代码块( <%%> )在服务器端控件中:

    // code behind, in the page_load event handler
    Bar.Value = 58;
    

    或者,在 ascx ,在服务器端控件之外:

    <% Bar.Value = 58; %>
    
        2
  •  7
  •   SLaks    14 年前

    把它改成

    <my:Foo ID="Bar" runat="server" Value="58" />
    

    ASP.NET分析器将自动分析整数属性。

    <%= ... %> 服务器端控件不支持表达式,因此代码会导致ASP.NET尝试(并失败)分析文本字符串 <%= Int32.Parse("58") %> 作为整数。