C# parameter on cs file can't be detected on aspx
So I have a condition on the aspx file:
<% if (yes)
{%>
{
<div>
<h1>hell yes!!</h1>
<p>Welcome</p>
</div>
<%}%>/
and here is my code on the page load
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
{
}
}
}
I get the error:
CS0103: The name 'yes' does not exist in the current context
I was wo开发者_如何学Pythonndering what I'm doing wrong...
yes
is a local variable; it doesn't exist outside of the Page_Load
method.
You need to create a public
(or protected
) property in the code-behind.
my suggestion, put this
public partial class _Default : System.Web.UI.Page
{
public string yes = "";
Then put
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
{
}
}
}
Hope it helps
If you make yes
a protected class-level variable it will work. The ASPX page is a separate class that inherits from the class defined in the code-behind.
You're declaring yes
within an if block - that's the scope of the variable. Once code execution exits the if block, your yes
variable will be queued up for garbage collection and you won't be able to access it.
One way to resolve this is declare a public property Yes
at the page's class level, which you can set within the Page_Load
method. Then you should be able to access it within the .aspx. Example:
public class MyPage : System.Web.UI.Page {
public bool Yes() { get; set; }
}
yes
is local to Page_Load
Either promote yes to a field or better yet, make it a public property of your class with a private setter:
public bool Yes { get; private set; }
精彩评论