开发者

Problem in variable declaration

开发者 https://www.devze.com 2023-02-26 03:26 出处:网络
On page load i am setting the value of String variable DB as follows: protected void Page_Loa开发者_运维知识库d(object sender, EventArgs e)

On page load i am setting the value of String variable DB as follows:

protected void Page_Loa开发者_运维知识库d(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
     String DB = "";
     DB = Session["db"].ToString();
    }
}

I want to use the variable DB (i want to pass this value to a method getpet()) in another method which is:

protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
    if(DropDownList2.SelectedItem.Text=="0")
    {
         petres d = new petres();
         String petitioner=d.getpet();
    }
}

How can i use a variable declared in one method, in another method?


Declare the variable at Page scope. Like this.

<%@ Page Language="C#" Debug="true" %>
<script runat="server">

    String DB = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
         String DB = "";
         DB = Session["db"].ToString();
        }
    }


    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if(DropDownList2.SelectedItem.Text=="0")
        {
            petres d = new petres();
            String petitioner=d.getpet();
        }
    }

</script>
<html>
<head>
    ...
</head>
<body>
...
</body>
</html>


This issue is due to scope resolution for the variable. If you need a variable in all the methods in a class, declare it at the class level.

For your case, you can declare it at class level and assign a value in the Page_load and then use it elsewhere.


If you declare a variable within a method's scope, you cannot access it from outside this scope. Try declaring it at class level, and assigning the value in your method.

class YourClass {

  protected String DB = "";

  protected void firstMethod() {
    DB = "whatever you want";
  }

  protected void secondMethod() {
    Console.writeln(DB);
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号