I'm learning C# and what I need is to access control on a Form from other class (the same namespace).
I know there is a lot of posts on this topic here but didn't find complete solution 'for dumbs' so I write here what I figured out and please tell me - is this the correct way ?
Background: I have some 'debugging' form in my app and I need all other forms to be able to log their activity into this form. There is some ListBox control where all the logs from other forms are written. When I (or one of my tester-friends without Visual Studio) play around with app and something bad happens, I can look on that debug-form to see all detailed logs what happened just before that 'moment of error'.
My main form of the app (frmMain):
namespace myNamespace {
public partial class frmMain : Form {
private frmDebug debug; // frmDebug is declared in other class
// we will hold reference to frmDebug form in 'debug'
public frmMain() { // constructor of the main form 'frmMain'
InitializeComponent();
debug = new frmDebug(); // we create new instance of frmDebug immediately when
} // our main form is created (app started) and whole time
// of running this app we can access frmDebug from
// within frmMain through 'debug' variable
// clicking button 'btnLoggingTest', the log is written
// in the 'frmDebug' form even if it is closed (not visible)
private void btnLoggingTest_Click(object sender, EventArgs e) {
debug.Log("log this text for me please");
}
// Click handler of the button 'btnShowDebug' :
private void btnShowDebug_Click(object sender, EventArgs e) {
debug.ShowDialog(); // here we can show frmDebug (in 'modal' style)
} // just to see what log-information is written there
} // frmMain class
} // namespace
And here is the code of class frmDebug itself :
(there is only one Listbox placed on the form)
namespace myNamespace {
public partial class frmDebug : Form {
public frmDebug() {
InitializeComponent();
}
public void Log(string txt) { // this is the actual 'Log' function (or method)
this.listBox1.Items.Add(txt);
Application.DoEvents(); // if the logging takes place in some
} // computing-intensive 'loop' or function,
// (or in my case FTP login and upload process)
// 'DoEvents' ensures every log appears immediately
// after the 'Log()' was called. Otherwise all logs
// would appear together at once, as soon as the
// computing-intensive 'loop' is finished
} // class frmDebug
} // namespace
I have a strange feeling in my stomach I'm doing it all wrong so please tell me how to do it properly :)
If it's OK, hope it helps somebody like me.
Thank you !