Accesing Richtextbox from a class - c#

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

Related

Why I can't Invoke from a different class?

My problem is, I can't invoke a message into the TextBox and I can't understand why.
There is a main class and a second class, both with call to the other one.
Where is my error?
using System;
using System.Windows.Forms;
namespace Class_Test___Invoke
{
public partial class MAINFORM : Form
{
public MAINFORM()
{
InitializeComponent();
_INVOKER = this;
}
private MAINFORM _INVOKER;
private static CLASS _CLASS = new CLASS();
private void button1_Click(object sender, EventArgs e)
{
_CLASS._MESSENGER();
}
public void _LOGGING(string _MESSAGE)
{
if (InvokeRequired)
{
_INVOKER.Invoke(new Action<string>(_LOGGING), new object[] { _MESSAGE });
textBox_ausgabe.AppendText(_MESSAGE);
return;
}
else textBox_ausgabe.AppendText(_MESSAGE);
}
}
}
namespace Class_Test___Invoke
{
class CLASS
{
private MAINFORM _MAINFORM = new MAINFORM();
public void _MESSENGER()
{
_MAINFORM._LOGGING("Test");
}
}
}
You are assuming that the _MAINFORM you create in the CLASS constructor is the same instance as the form where the button was clicked, which is not the case. You have a chicken-and-egg problem. Your form creates a CLASS, and the CLASS creates a form. So now you have two different forms. (or two different CLASS instances since you don't show how the first form or CLASS is created)
You need to "connect" the form and the class, either by passing the form to the constructor as a parameter or by some other means.
Finally, I would encourage you to do some research on best practices for class and member names. It's a bit disconcerting for a seasoned C# developer to see names in all caps and prefaced by underscores.

Sending data between 2 windows forms of which one is singleton

I have following problem i have 2 windows forms and to send data between them i figured out that in Form2(which is called by Form1) constructor i will be passing reference to Form1 .
Like this public Form2(Form callingForm)
{
mainForm = callingForm as Form1;
InitializeComponent();
}
But I would like Form2 to be singleton and somehow I don't know how to achieve that along with passing form1's reference to form2. I reviewed documentation https://msdn.microsoft.com/en-us/library/ff650316.aspx and I have no clue how to edit this example to fit my needs. So I am able to make singleton constructor or make constructor that takes reference to form1, but not both.
If Form1 is your application's Main Form then you should use --> Appliction.MainForm. That way you don't need the parameter.
Edit: I was not trying to be obtuse and not answer your question. You can create a singleton with parameters using multiple constructors, however, I would try to avoid it.
private Singleton(param1,param2)
public static Singleton MyInstance(param1,param2)
I am not sure I am understand your question very well, but I think, you can implement Lazy.. (Lazy itself implements Singleton pattern). Maybe something like this:
class Form1
{
public Form2 Callee
{
get;
set;
}
public Form1()
{
Callee = Form2.Instance(this).Value;
}
}
class Form2
{
public static Lazy<Form2> Instance(Form1 caller)
{
return new Lazy<Form2>(() =>
{
return new Form2(caller);
});
}
public Form1 Caller
{
get;
private set;
}
Form2(Form1 caller)
{
Caller = caller;
}
}
Ok i seem to have solved this problem, here is the code:
private Form1 mainForm = null;
public Form2(Form callingForm)
{
mainForm = callingForm as Form1;
InitializeComponent();
}
public static Form2 Instance
{
get
{
if (instance == null)
{
instance = new Form2(Application.OpenForms[0] as Form1);
}
return instance;
}
}
#lrb thank you, basically i had problem in this line, cuz couldn't pass anything as parameter
instance = new Form2(Application.OpenForms[0] as Form1);
and Application.OpenForms[0] helped.

how to edit the primary form using a form that was created from the primary form in C#

I want to edit a primary form(Form1) using a form that is created from its code(Form2). The way I have done it is that, when the event is triggered, the new form appears, and everything works, but I want it so that when a button is pressed, the original form is edited. The code I have tried is this:
Form1 form1 = new Form1();
private void button1_Click(object sender, EventArgs e)
{
form1.startNewGame();
this.Hide();
}
By the way, I realise that this is creating a new instance of the form, I want to know how to edit the already existing instance of the form.
Without having the code of Form2 is hard to help you, but I will try. Instead of creating an instance of Form1, add a public property to form2
public Form1 PrimaryForm{get;set;} and when you showin form2 set that property to this
A solution would be to pass a reference of your Main Form to the child form when the child form is initialized. You can then set the value of the mainform through the reference. See below for an example:
public class ChildForm1 : Form
{
// Fields
private MainForm _mainForm;
private bool _value1;
private bool _value2;
// Default constructor
public ChildForm1()
{
}
// Overloaded constructor that accepts a container of values
public ChildForm1(ValuesContainer values, MainForm mainForm)
{
_mainForm = mainForm;
_value1 = values.Value1;
_value2 = values.Value2;
//Set a main form value
_mainForm.Value = "This value was changed by ChildForm1."
}
}
public class ChildForm2 : Form
{
// Field
private bool _value3;
// Default constructor
public ChildForm2()
{
}
// Overloaded constructor that accepts a container of values
public ChildForm2(ValuesContainer values)
{
_value3 = values.Value3;
}
}
public class MainForm : Form
{
public string Value { get; set; }
// Default constructor
public MainForm()
{
}
// Simulated - Event method called when button is clicked for child form 1
public void CallChildForm1()
{
ValuesContainer values = new ValuesContainer();
// Set the values from the main form
values.Value1 = true;
values.Value2 = true;
// Call the child form while passing in the container of values that we just populated.
ChildForm1 childForm = new ChildForm1(values);
childForm1.Show();
}
// Simulated - Event method called when button is clicked for child form 2
public void CallChildForm2()
{
ValuesContainer values = new ValuesContainer();
// Set the value from the main form
values.Value3 = true;
// Call the child form while passing in the container of values that we just populated.
ChildForm2 childForm = new ChildForm2(values);
childForm2.Show();
}
}
// Simple data object or container used to transfer information between complex objects such as forms and controls.
// These are also known as data classes or data transfer objects (DTOs)
public class ValuesContainer
{
public bool Value1 { get; set; }
public bool Value2 { get; set; }
public bool Value3 { get; set; }
}
This might not be the best practice but is the simplest way to do it. Here are the steps;
1) in Form1 add a public method to edit whatever you want
2) in Form2 add a reference to type Form1
3) instantiate Form2 and set InstanceOfForm2.ReferenceToForm1 = this;
4) in the event handler of Form2 use the reference to call your public method like
//inside some event handler
this.ReferenceToForm1.MyPublicMethodThatEditsTheDisplay();
One thing to remember is that Form1 is just an object like any other. The only thing preventing you from editing it anywhere you choose is the access level of it's properties (can't touch private fields, obviously) and the lack of reference. Everything beyond that is a matter of opinion and 'best practice' if you want to edit from anywhere, make the field public/provide a public method and pass/set a reference.

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

Instantiate in the class

I am working on something and I have to instantiate the class. My question is where would I do that at? Would I do it before this:
public partial class Form1 : Form
{
InputClass myclass = new InputClass();
public Form1()
{
InitializeComponent();
}
Or
public partial class Form1 : Form
{
public Form1()
{
InputClass myclass = new InputClass();
InitializeComponent();
}
Here is another code I am working on but it is not working out to well this is what my code looks like right now:
public partial class Form1 : Form
{
InputClass myClass = new InputClass();
myClass.yourname = "";
myClass.Banner = "";
public Form1()
{
InitializeComponent();
}
I am new to C# and I am trying to figure this out. I need to instantiate the class. Then when the page load add to set the labels text from the _banner variable. Then add code to set the property yourname from the text in the textbox when the user presses the button. Then i need to clear the textbox. I also have to display the name in a messagebox from the class.
class InputClass
{
public string _banner;
private string _yourName;
public InputClass(String _banner)
{
this._banner = _banner;
}
public string yourName
{
get { return _yourName; }
set { _yourName = value; }
}
}
}
If you want to access your object from other methods in your class then you need to use a member field rather than a local variable.
private InputClass myClass = new InputClass { YourName = "", Banner = "" };
public Form1()
{
InitializeComponent();
}
Another option is to declare a member field but initialize it inside the constructor:
private InputClass myClass;
public Form1()
{
InitializeComponent();
this.myClass = new InputClass { YourName = "", Banner = "" };
}
This isn't too useful in your specific case, but it can be useful if you need to pass parameters from your constructor to the InputClass constructor.
You can only set the properties inside a function body! not inside the class context.
Instantiating the class would work inside Form1() or at declaration time. IMO best style in your case would be:
public partial class Form1 : Form
{
InputClass myclass;
public Form1()
{
InitializeComponent();
myclass = new InputClass();
}
}
This enables one to use myClass not only in the Form1 constructor, but also in any other function.
First of all, make the distinction between Declaration and Instantiation. In your first snippet, you're declaring the InputClass member in the class scope, meaning it will be shared by all methods in the class. Once you do that, it doesn't matter if you instantiate it in the constructor or during declaration, it (mostly) works out to the same thing.
Secondly, I'm guessing that this is an ASP.NET project, since you refer to "page load". If so, remember that your Form1 instance doesn't stay alive between page loads. Every time you reload the page, either manually with F5 or via button-clicks/postbacks, you're creating a new instance of Form1, which will create a new instance of InputClass.
What you're doing in the first example is a declaration of a member variable of Form1 named myclass. You can assign it a value at the same place, which is fine:
public partial class Form1 : Form
{
InputClass myclass = new InputClass();
public Form1()
{
InitializeComponent();
}
}
But you usually cannot insert actual code statements in your class declaration (like the assignment myClass.yourname = ""). You need to put them in the constructor. So a correct way to do this would be:
public partial class Form1 : Form
{
InputClass myClass = new InputClass();
public Form1()
{
myClass.yourname = "";
myClass.Banner = "";
InitializeComponent();
}
}
For performing actions on button click, look here: http://msdn.microsoft.com/en-us/library/43sxkdeb(v=vs.80).aspx

Categories

Resources