C#- using a variable in an 'enclosing' local scope? - c#

I am trying to add some new features to a C# application- in particular, trying to replicate some of its behavior, but inside a web browser, rather than in the application, as it currently is.
I am trying to call a method that has been defined in the Browser.cs class from inside a method in the MainWindow.cs class.
The method is defined in Browser.cs with:
public partial class Browser : Form{
public Browser(){
...
}
public void Browser_Load(object sender, EventArgs e){
webKitBrowser1.Navigate("https://google.com");
}
...
}
I am then trying to call it from MainWindow.cs as follows:
public partial class MainWindow : Window{
...
public MainWindow(){
...
Browser mBrowser = new Browser();
Object sender = new Object();
EventArgs e = new EventArgs();
mBrowser.Browser_Load(sender, e);
...
}
...
}
But, I'm getting a compile error that says:
A local or parameter named 'e' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
What does this mean? I've never come across this error before- I am using the variable inside the same scope as where it has been declared- what does it mean by 'enclosing local scope'? Is that because I'm using e inside the parenthesis for the method call to mBrowser.Browser_Load(sender, e)?
Surely, since the call to this method is inside the same scope as where I've defined e, it shouldn't be an issue of scope?
I did try performing the call with:
mBrowser.Browser_Load(sender, EventArgs e);
but this gave me a compile error saying:
'EventArgs' is a type, which is not valid in the given context.
Can anyone point out what I'm doing wrong here, and what I should be doing to be able to call this method correctly?

The error is pretty clear, you have already defined e named variable in your scope, (Probably in the part of code that you haven't shown).
But more importantly, you shouldn't be calling the Load event like that, instead extract the functionality in a separate method and call the method from your Load event and other places.
Like:
public void SomeMethodToBeCalledOnLoad()
{
webKitBrowser1.Navigate("https://google.com");
}
public void Browser_Load(object sender, EventArgs e)
{
SomeMethodToBeCalledOnLoad();
}
public MainWindow(){
...
Browser mBrowser = new Browser();
Object sender = new Object();
EventArgs e = new EventArgs();
SomeMethodToBeCalledOnLoad();//here
...
}

You already have a variable named e in the scope.
try to call your method like this
mBrowser.Browser_Load(this, EventArgs.Empty);
and the error should go.

Related

How to call a function in page load asp.net?

The function below is found in a class called page.cs
public static List<string> MyFunction()
{
var retList = new List<string>();
retList.Add("xzy");
retList.Add("abc");
return retList;
}
On page load how to call the function and check if the list contains
xzy and abc?
protected void Page_Load(object sender, EventArgs e)
{
//call MyFunction()
}
You don't really show enough code for us to see your problem. As I read it, you have a class Page in a file named page.cs and it looks like this in part:
public class Page {
public static List<string> MyFunction()
{
var retList = new List<string>
{
"xyz",
"abc",
};
return retList;
}
protected void Page_Load(object sender, EventArgs e)
{
var list = MyFunction();
}
}
(Note that I've simplified your initialization of the list - my code is equivalent to yours)
The code I show compiles. Assuming that MyFunction and Page_Load are in the same class, then you can directly call MyFunction from Page_Load (static functions can be called from instance function (within the same class)).
If they are not in the same class, let's say that MyFunction was a static function in another class (say OtherClass). Then Page_Load could call it in the way #joelcoehoorn describes:
OtherClass.MyFunction();
The reverse is not true. A static function cannot directly call an instance function (one without the static keyword) in the same class. You'll get an error complaining that you need an instance. For example, if MyFunction wanted to call Page_Load, it would need to do something like this:
var page = new Page();
//possibly do something with page
page.PageLoad(new object(), EventArgs.Empty);
//possibly do more stuff with page
If this doesn't answer your question, you need to add more to your question. In particular:
Show the class declarations around your method definitions. It's not clear (but it is important) which class(es) have which methods
Show us the code you have and any error messages you get (compile time and runtime)
Also note that I don't believe you should be getting Non-invocable member 'page' cannot be used like a method. if you did what #joelcoehoorn describes.
You have to reference the function using the type name. However, a file named page.cs likely had a class named Page, which will conflict with the base ASP.Net Page class. Therefore you must either fully-qualify the name (MyNamespace.Page.MyFunction()) or change the name of the class.

Issues with scope in listener methods [duplicate]

This question already has answers here:
The name 'str' does not exist in the current context
(2 answers)
Closed 3 years ago.
I want to be able to reference the Reaction object of the EquationClass class from all of the methods in this CalculatorPage class. I declared the Reaction object in the first event listener method. The second event listener however can't access the instance of the class and I'm not sure how to fix it.
I tried changing the first method to public but the error persisted.
private void ExampleListenerMethodOne(object sender, RoutedEventArgs e)
{
var Reaction = new EquationClass("Example");
Reaction.species = Reaction.MakeAndReturnSpeciesArray();
}
public void ExampleListenerMethodTwo(object sender, RoutedEventArgs e)
{
Console.WriteLine(Reaction.species); //Here is the 'Does not exist
//in current context error'
}
I would expect to be able to access the object from anywhere but I can't.
I get a "does not exist in current context error" from visual studio. I have read the other questions that are related but I couldn't find a solution.
Just turn it to a property. Here the class instantiates a new variable of type Reaction (with whatever you need to do to do it). Therefore, the myReaction variable is in a class level scope to the two methods below that need it. Previously, your variable was in a method scope meaning it can't be used outside of the method. There is also a block scope for variables defined in a code block such as if statements with a variable defined within the if statement.
public class MyClass
{
public Reaction myReaction { get; set; }
public MyClass()
{
myReaction = new EquationClass("Example");
}
private void ExampleListenerMethodOne(object sender, RoutedEventArgs e)
{
myReaction.species = Reaction.MakeAndReturnSpeciesArray();
}
public void ExampleListenerMethodTwo(object sender, RoutedEventArgs e)
{
Console.WriteLine(Reaction.species);
}
}

Method not returning a value

I have a method that should return the domain name of the current user in a label.text. I call the method in the load event of the form but nothing comes up, no errors in the code either. Maybe im starting the object wrong? It works if i put the method code in the load event directly.
public partial class Main Form
{
public Main()
{
InitializeComponent();
}
public string getCurrentDomain()
{
return domainNameValue.Text = Environment.UserDomainName;
}
public void Main_Load(object sender, EventArgs e)
{
Main main = new Main();
main.getCurrentDomain();
}
}
I think your problem is in the Main_Load function you are creating a new form instead of changing the current form, The correct code is:
public void Main_Load(object sender, EventArgs e)
{
this.getCurrentDomain();
}
Or if you wnat to have another form just show it using main.show()
The problem is because you are creating new instance of Main class in your Main_Load method. So, the method getCurrentDomain() change label text of the instance that you are creating not the label in the form where Main_Load is executed.
Also the body of method getCurrentDomain() violates the Principle of least astonishment because that method is generating side effect which changes text of a label. But the name of method suggest only that the current domain name is being returned.
You could use
public string getCurrentDomain() // Method: Get current domain
{
domainNameValue.Text = Environment.UserDomainName;
return Environment.UserDomainName;
}

The name 'GetInvestPeriod' does not exist in the current context

I have an ASP.net solution, which contains a project InvestTracking where I am calling a function GetInvestPeriod() from the PageLoad event.
I have another project InvestTrackingBL which contains the function GetInvestPeriod().
protected void Page_Load(object sender, EventArgs e)
{
GetInvestPeriod();
}
public class InvestTrackingBL
{
protected void GetInvestPeriod()
{
}
}
I am getting an error in my main project:
'The name GetInvestPeriod does not exist in the current context'.
What am I missing here?
You can't just use the function like that.
You either need an instance of InvestTrackingBL or call the static method on it:
//If it's an instance member
var investTrackingBL = new InvestTrackingBL();
investTrackingBL.GetInvestPeriod();
//or if it's static
InvestTrackingBL.GetInvestPeriod();
And following your update. Methods that are protected cannot be called by other classes, only derived classes, you need to make it public or internal.

Issue running C# function from another C# application

I have a C# Windows Form that contains a function called automation. I then have a C# console application that I am trying to use to call the function of the Windows Form. I have created the reference and have gotten this far:
Form1 FormInstance = new Form1();
FormInstance.automation += new EventHandler(?);
My question is, I have tried to add something where my question mark is but I continue getting an error. If I set it up like this:
FormInstance.automation += new EventHandler(NewHandler);
I get "NewHandler" does not exist in the current context.
And if I create
public void NewHandler(object sender, EventArgs e)
I get An object reference is required for the non-static field, method, or property.
I can not figure out what I am doing wrong.
It is supposed to be object.NewHandler, where object may be this if this occurs within the context of a member method. You can be forgiven for tripping this up because most member references can be implicit but this one has to be explicit.
At a high level it works something like this:
public static void Main(string[] args)
{
Form x = new Form();
x.Method = new EventHandler(MyHandler);
}
public static void MyHandler(object sender, EventArgs e)
{
// Stuff
}
It looks like you haven't marked your method with the static keyword (if invoking this via a static method like a console main). You also need to make sure you're assigning the appropriate delegate to the event; i.e. automation in your method needs to be able to accept an EventHandler delegate.
The simplest way is to make your event handler method static
public static void NewHandler(object sender, EventArgs e)

Categories