I'm very new to Windows Form programming, and I'm coming across a problem.
I have a windows form, Form1
, with a textbox: tbx_Log
.
In another class in the same project, I want to write something to the log textbox, but I cannot reference tbx_Log in that class. How can I achieve this?
Windows. Forms as a reference in your project. Right-click on 'References' , select 'Add Reference' and look under Assemblies in the dialogue. If you created your project as a Windows Forms project, that reference should have been added for you automatically.
The <see> tag can be used to link to another class. It contains the cref member which should contain the name of the class that is to be referenced. Visual Studio will provide Intellsense when writing this tag and such references will be processed when renaming the referenced class, too.
Click on File >> New >> Project menu and select WPF Application from Templates as shown in Figure 1. In Solution Explorer, right click on References node and select Add Reference menu item. On Browse tab, go to "C:\Program Files\Reference Assemblies\Microsoft\Framework\v3. 0" folder and select WindowsFormsIntegration.
Accessing objects inside other class instances (objects) is bad style and violating data encapsulation. Add a method to Form1
:
public void SetLogText(String text)
{
tbx_Log.Text = text;
}
This way you can change the implementation of the method by using some other control or logging to a file later, without having to modify all the call sites. Always try to have the code outside the class not to have knowledge about what's inside. The class implementation shall be a "black box" for the outside code.
You either need to make the textbox public (not recommended) or add a public method to your form class that will write a string to the textbox (better).
public class Form1
{
protected Textbox tbx_Log;
public void Log(string str)
{
tbx_Log.Text += str + Environment.NewLine;
}
}
public class Program
{
private void DoStuff()
{
Form1 myForm = new Form1();
//Make form visible, etc...
myForm.Log("Test Log");
}
}
I'd suggest that you create a method on the Form class that writes to the log textbox. Then you would pass that method as a delegate (callback) to your non-Form class. This gives you more flexibility down the road. For instance, if you wanted to call the same class from a different class, and you wanted to do something different with the logging information, such as writing it to a file, then you could just pass a different callback function.
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