0

所以我对aspx文件有一个条件:

<% if (yes)  
   {%>
   {
<div>
    <h1>hell yes!!</h1>
    <p>Welcome</p>
</div>
<%}%>/

这是我在页面加载时的代码

protected void Page_Load(object sender, EventArgs e)
{
  if (accnt != null)
    {
        using (SqlConnection conn = new SqlConnection(connectionstring))
         {
            conn.Open();
            string strSql = "select statement"
                      :
                      :
            try
            {
                if (intExists > 0)
                {
                    bool yes= check(accnt);
                }
            }
            catch
            {
            }
        }
    }

我得到错误:

CS0103: The name 'yes' does not exist in the current context

我想知道我做错了什么......

4

5 回答 5

2

yes是局部变量;它不存在于Page_Load方法之外。
您需要在代码隐藏中创建一个public(或)属性。protected

于 2011-03-10T20:00:27.387 回答
1

如果您创建yes一个受保护的类级变量,它将起作用。ASPX 页面是一个独立的类,它继承自代码隐藏中定义的类。

于 2011-03-10T20:00:57.327 回答
1

我的建议,把这个

public partial class _Default : System.Web.UI.Page 
{
    public string yes = "";

然后放

protected void Page_Load(object sender, EventArgs e)
{
  if (accnt != null)
    {
        using (SqlConnection conn = new SqlConnection(connectionstring))
         {
            conn.Open();
            string strSql = "select statement"
                      :
                      :
            try
            {
                if (intExists > 0)
                {
                    bool yes= check(accnt);
                }
            }
            catch
            {
            }
        }
    }

希望能帮助到你

于 2011-03-10T20:02:29.510 回答
0

您在yesif 块中声明 - 这是变量的范围。一旦代码执行退出 if 块,您的yes变量将排队等待垃圾收集,您将无法访问它。

解决此问题的一种方法是Yes在页面的类级别声明一个公共属性,您可以在Page_Load方法中设置它。然后您应该能够在 .aspx 中访问它。例子:

public class MyPage : System.Web.UI.Page {
  public bool Yes()  { get; set; } 
}
于 2011-03-10T20:03:16.607 回答
0

yes是本地的Page_Load 要么将 yes 推广到某个字段,要么更好,使用私有 setter 将其设为类的公共属性:

public bool Yes { get; private set; }
于 2011-03-10T20:03:50.747 回答