【问题标题】:User control variable not declared未声明用户控制变量
【发布时间】:2013-02-21 00:57:21
【问题描述】:

我有一个在用户控件中声明的变量。它是用户控件中下拉列表的值。当我尝试在 aspx 页面上的 If 语句中使用它时,它说未声明该变量。有没有办法在aspx页面上声明变量或者让它识别出它是在用户控制页面上声明的?
谢谢

我正在调用 aspx 页面顶部的代码

<%@ Register src="pType.ascx" tagname="pType" tagprefix="uc2" %>

我正在使用 if 语句

<%If pt.SelectedValue = "1" Then%>
    \\do things 
    <%End If%>

在控件中pt由定义

<asp:DropDownList ID="pt" runat="server">

【问题讨论】:

  • 如何将用户控件嵌入到 aspx 页面中。也许提供一个代码 sn-p,说明您如何嵌入控件并尝试访问变量。
  • 谢谢!我添加了一些代码

标签: asp.net .net vb.net user-controls


【解决方案1】:

我认为您不能在 aspx 页面中访问用户控件的属性。

我知道你可以做的是在后面的代码中声明用户控件并将其动态添加到你的页面中。

protected void Page_Init(object sender, EventArgs e)
{

      //MyControl is the Custom User Control with a code behind file
      MyControl myControl = (MyControl)Page.LoadControl("~/MyControl.ascx");

      if (myControl.SelectedValue == 1) {
         //do work
      }
      // User Control is a placeholder in your aspx page
      UserControlHolder.Controls.Add(myControl);

}

【讨论】:

    【解决方案2】:

    我可能需要查看代码,但您尝试过吗

    var v = pt.SelectedItem;
    
    if (v == "1")
    {
    // do things
    }
    

    请注意,此代码需要在代码后面(.cs)文件中运行,而不是 ascx 或 aspx 文件:)

    【讨论】:

    • 我不确定我是否理解您的回答,但我非常感谢您的宝贵时间。我添加了一些代码以进行澄清,这对您有意义吗?谢谢!
    • 这段代码应该用在你的控件后面的代码中,而不是在标记中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多