I have a problem, after adding this code so I can access my MainWindow controls in Downloader class:
public partial class MainWindow : Form
{
private Downloader fileDownloader;
public MainWindow()
{
InitializeComponent();
fileDownloader = new Downloader(this);
}
//smth
}
and
class Downloader : MainWindow
{
private MainWindow _controlsRef;
public Downloader(MainWindow _controlsRef)
{
this._controlsRef = _controlsRef;
}
// smth
}
it now gives me "An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll" on line
this.mainControlPanel.ResumeLayout(false);
in MainWindow.Designer.cs. If i comment out the code above, it works fine. Any ideas please?
PS. Also, when I'm in Downloader class, should i access the controls like
textbox.Text
or
_controlsRef.textbox.Text
Both seem to give no compile errors, is there any difference between the two?
Your Downloader class inherits MainWindow. When you instansiate it, according to the C# specification, the base class is initialized first. When MainWindow initializes, it creates a new instance of Downloader, which causes it eventually to stackoverflow, because you're in an endless cyclic dependency.
Since Downloader inherits MainWindow, there is no point in getting an instance of it via your constructor. You can simply access it's protected and public members from your derived.
For example:
public partial class MainWindow : Form
{
protected string Bar { get; set; }
public MainWindow()
{
Bar = "bar";
InitializeComponent();
}
}
public class Downloader : MainWindow
{
public void Foo()
{
// Access bar:
Console.WriteLine(Bar);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With