I have Form1 with Textbox. Form1 call class1, class1 call class2. So how to set Textbox from class2 without passing Form1 as variable.
Asked
Active
Viewed 261 times
-1
-
1Show your code you tried to do it? – TriV Apr 17 '17 at 04:15
-
Only `Form1` should have access to the textbox. There are a variety of decoupled ways to accomplish this. Depending on the exact scenario, it's likely one of the best ways is for `class2` to expose an event that is raised at the time new text is available to be set. Then `Form1` can subscribe to the event and retrieve the text itself. You may need to reflect this event in `class1` as well; again, depends on the exact scenario (you've provided practically no context). See [my answer here](http://stackoverflow.com/a/29872737) for an example of how the event-based approach would work. – Peter Duniho Apr 17 '17 at 04:16
1 Answers
0
your question is so unsightly but here delegate
is one of the approach to achieve your scenario here is an example please refer it.
// FORM1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Class1 cls1 = new Class1();
cls1.textChange += Cls1_textChange; ;
cls1.YourFunctionInClass1();
}
private void Cls1_textChange(string str)
{
textBox1.Text = str;
}
}
// CLASS1
public class Class1
{
internal delegate void TextChangeDelegate(string str);
internal event TextChangeDelegate textChange;
public void YourFunctionInClass1()
{
Class2 cls2 = new Class2();
cls2.textChange += Cls2_textChange;
cls2.YourFunctionInClass2();
}
private void Cls2_textChange(string str)
{
textChange(str);
}
}
// CLASS2
public class Class2
{
internal delegate void TextChangeDelegate(string str);
internal event TextChangeDelegate textChange;
public void YourFunctionInClass2()
{
textChange("Hello I am from Class2");
}
}

Darshan Faldu
- 1,471
- 2
- 15
- 32