Reputation: 4028
On page load i am setting the value of String variable DB
as follows:
protected void Page_Load(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?
Upvotes: 0
Views: 409
Reputation: 2826
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>
Upvotes: 1
Reputation: 1150
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);
}
}
Upvotes: 0
Reputation: 15571
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.
Upvotes: 0