How to access a visual component from another form in c# - c#

I have a textbox in my main form.
Now I have created a function which is used to set the value of the text box.
public void SetTextOfTextBox(String text)
{
textbox1.text = text;
}
Now in my main form I call another class (class b) which does some work for me. Now i want to be able to call my setTextofTextBox function from class b.
Now if I try Form1.SetTextOfTextBox("test"); this doesn't work.
What am I doing wrong?
How do I access components of a a Form from another class.

Form1.SetTextOfTextBox("test"); this doesn't work
This doesn't work because SetTextOfTextBox is not static and you cannot access a non-static function directly. And you can't make it static either because your textbox is form level control.
How do I access components of a a Form from another class
You will have to pass the instance of Form1 to your other class to access it. Something like
Class B = new ClassB(this); //where this is the instance of Form1.

You will need a reference to the instance of Form1 in class b, otherwise you cannot call member methods.
Something like this:
class Form1 : System.Windows.Forms.Form {
void functionInForm1() {
ClassB objB = new ClassB();
objB.doSomething(this);
}
}
class ClassB {
void doSomething(Form1 form) {
form.SetTextOfTextBox("test");
}
}

Find out the Form1 and call the method:
foreach (var form in Application.OpenForms) {
Form1 myForm = form as Form1;
if (!Object.ReferenceEquals(null, myForm)) {
myForm.SetTextOfTextBox("Test");
break;
}
}

Did u try using delegates.
Specify the delegates in your ClassB like this.
public delegate void OnDone(string textValue);
public event OnDone OnUserDone;
after completing the task in ClassB call event:
OnUserDone("DoneClassB");
When u create the object of class in form map delegate function.
Classb b=new Classb();
b.OnUserDone += new Classb.OnUsrControlDone(CompletedClasss);
Define the function in form like below.
void CompletedClasss(string textValue)
{
SetTextOfTextBox( textValue);
}

Related

creating a new object triggers an exception c#

When I create a new thing from the MyClass class it triggers an exception.
namespace class_test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MyClass thing = new MyClass();
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = thing.x.ToString();
thing.x++;
}
}
code for the class:
namespace debugging_class
{
class MyClass : Form1
{
public int x = 100;
}
}
By testing I found out that the : Form1 from the class code is the issue. I am using that because I want to access Form1 objects in the class. Is there any way to do that without using : Form1?
The problem is indeed one of infinite recursion. When you create a MyClass object, it calls the constructor for that class. Because MyClass inherits from Form1 and you haven't specified a default (parameterless) constructor for MyClass, it will implicitly call the constructor for Form1.
The problem is that you have in your code for Form1 a class-level variable with a default value. When a class has a field with a default value, those variables will be implicitly set with the given value at the beginning of that object's constructor. So, for example, the code:
public class SomeClass
{
public int i = 5;
public SomeClass()
{
// Just a simple call and that's it
Console.WriteLine(i);
}
}
Will actually compile to something resembling the following:
public class SomeClass
{
public int i;
public SomeClass()
{
// Assign default values to class instance fields
i = 5;
// Execute the rest of the constructor code
Console.WriteLine(i);
}
}
So here is the problem - your Form1 class has a MyClass field with a default value of new MyClass(). That field will be assigned in Form1's constructor. Because MyClass inherits from Form1, then Form1's constructor will also get called, which will then create a new instance of MyClass, which will call the constructor for Form1 again... You see how this turns into infinite recursion? The constructors of Form1 and MyClass are calling each other back and forth forever and ever (or at least until the program reaches the limit of recursion and throws a StackOverflowException).
The reason that your code runs fine if you remove the default value and instead put the instantiation of the field inside a separate method is because that method won't get called until later in your program. MyClass's constructor will call Form1's constructor and then return, allowing your program to continue on its merry way.

How do i pass/use a method from form1 in a new class?

In form1 i have a method i changed it to public:
public bool ComparingImages(Bitmap File1)
{
}
Then i created a new class and did:
private Form f1;
public SimulateDownloads(Form form1)
{
f1 = form1;
}
Then in the new class bottom in another method i did:
bool downloaded = f1.ComparingImages(test);
But f1 does not contain ComparingImages
I tried also to add to form1 constructor:
private SimulateDownloads simdownloads;
public Form1()
{
InitializeComponent();
simdownloads = new SimulateDownloads(this);
But i don't want to run the program first i want to be able now without running the program to call the method ComparingImages in form1 to call it from the new class.
The problem you're having is that your SimulateDownloads method is taking in an object of type Form instead of type Form1. Remember, you put the public method on a class called Form1, you did not add it to the base Form class!
Try this:
// (This is in your other form, not Form1)
private Form1 f1;
public SimulateDownloads(Form1 form1)
{
f1 = form1;
}
Then you should be able to do this in your other form:
bool downloaded = f1.ComparingImages(test);
It sounds like your ComparingImages shouldn't be in the form1 at all. Create a new class Utils or similar and put ComparingImages in that class. Then you can use
bool downloaded = new Utils().ComparingImages(test); //or Utils.ComparingImages(test); if you make it static
from both SimulateDownloads and form1

Accesing Richtextbox from a class

I'm trying to append text in my richtextbox which is called ConsoleText. It's not working very well. I'm using a property in my form to access the richtextbox in the Class.
It looks like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Skipped the rest
public string ACText
{
set
{
ConsoleText.AppendText(value);
}
}
Now from my class's constructor.
public McDonalds(string email, string pass)
{
Form1 f = new Form1();
f.ACText = "test";
}
It's not showing any text in my richtextbox sadly. I know it works, because i can in the property use a messageBox and see that the value is passed into it.
Thanks in advance i really need help with this.
Calling Form1 f = new Form1(); does not give you a reference to an existing form, it creates a new one with blank/default values in the form's controls.
HOW to solve this greatly depends on your design. If you want to tie your class to that form implementation, our class needs either a reference to the form, a reference to the control, or the value of the control that you're interested in passed to it.
For example:
public McDonalds(string email, string pass, Form1 form)
{
form.ACText = "test";
}
A cleaner solution would be to RETURN a value from your McDonalds class and let the FORM set the control value appropriately rather than tying your class to that form class.
you can use Singleton:
Singletons make having single instances easy. They allow for single allocations and instances of data. We review the singleton types. We see one of the fastest implementations. And we review other possibilities.
public partial class Form1 : Form
{
public static Form1 instance = null;
public Form1()
{
instance = this; //add this class to singleton
InitializeComponent();
}
public void Show(string Message)
{
MyConsole.Text = Message;
}
another class:
Form1.instance.Show("blah blah");
Create Delegate in Form1 Class binded method ACText (string val), and Pass the Delegate to McDonalds Class. Fire the Delegate
namespace YourNameSpace
{
public delegate void RichTextBoxDelegate(string text);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void ACText(string s)
{
ConsoleText.AppendText(s);
}
// In Some Method Call MCDonald's form
public void ShowMcDonalds()
{
RichTextBoxDelegate deleg = new RichTextBoxDelegate(ACText);
MCdonalds ob = new McDonalds(deleg);
ob.show();
}
}
}
Pass the deleg to McDonalds form
Just fire the Delagate
public McDonalds(RichTextBoxDelegate sp)
{
Form1 f = new Form1();
sp("This is Test");
}
deleg("Test value"); // form McDonald's Form

Changing controls properties from other class

I'm using CompactFramework to make a WinCE App.
I have a Form1 and a Class1. In the Form1 I have a label1 which I need to get access from Class1.
If I try:
Form1.label1
it doesn't appear, despite I set Modifier property to public.
How could I get access to the label?
Thanks for any help!
The issue is that Form1 is a class, and you need an instance of that class, because your label is not static.
var myForm = new Form1();
myForm.label1.Text = "hello";
Obviously you don't want to create the new form from your class, because your application likely created the form.
So you should pass the form into the class. Does the class get instantiated by the form? If so you can pass "this" into the class to send a reference to the instantiated form.
But really, you don't want to do this, because its difficult to maintain. Better would be to have the class raise some sort of event that the form could subscribe to to update itself.
You can instance Form1 to Class1 and then use this instance to set Form1.label1.
This would be an elegant solution. Check this code:
public partial class Form1 : Form
{
public Label Label1 { get; set; }
public void Caller()
{
MyClass cls = new MyClass();
cls.Form1 = this;
cls.DoSomeJob();
}
}
public class MyClass
{
public Form1 Form1 { get; set; }
public void DoSomeJob()
{
Form1.Label1.Text = "Some text...";
}
}
Try to create property or method on the Form1 class to return label1 object

Call panel.invalidate outside form class in C#

I need to call "panel.invalidate" outside my form (WINform) class also I need to change some other controls as well, I read similar question here, and tried what they said, but it didn't work and I wasn't convinced at all.
The answer I read was about exposing a public method like this:
public void EnableButton(bool enable)
{
this.myButton.Enabled = enable;
}
Also I made a static instance in the other file
static Form1 myForm = new Form1();
Any useful suggestions??
The problem is the "myForm" reference. It is a reference to an instance of Form1 that isn't visible and doesn't match the one that the user is looking at. It can't be a match, you created a new one.
Whatever class needs to update the form must have a constructor that takes a Form1 reference. You can create the class object in your Form1 constructor or Load event, pass "this". Using Application.OpenForms[0] is another way to get the reference, one you should not use.
Are you updating from the same thread? Otherwise you might need to use Invoke.
Here's a nice short article about how to do that:
http://blogs.msdn.com/csharpfaq/archive/2004/03/17/91685.aspx
Control.Invalidate() is a public method, but the control itself is most likely not public. You will have to expose the call to Control.Invalidate() through a public facing method in your form or by marking the control in question as public.
public class MyForm : Form {
private TextBox tbxName = new TextBox();
public InvalidateTextBox() {
tbxName.Invalidate();
}
}
OR
public class MyForm : Form {
public TextBox tbxName = new TextBox();
}
public class SomeOtherClass {
public void InvalidateTextBox(MyForm form) {
form.tbxName.Invalidate();
}
}

Categories

Resources