I'm having a problem with delegate. In my project I have 2 forms, form1 and form2. From form1 I have a button there just for opening form2. And from form2 I have a text box there to enter an Int value. After getting a value from the text box I want to send it back to form1 and appear in a text box on form1.
I do this with a delegate but I don't know if my way is the way you use to solve this problem or not.
Here is my code:
Form1
public delegate void TestDelegate(int i);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frmOpen = new Form2();
frmOpen.ShowDialog();
}
public void GetValueA(int i)
{
textBox1.Text = i.ToString();
}
}
Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int b;
b = Convert.ToInt32(textBox1.Text);
Form1 frm1=new Form1();
TestDelegate td = new TestDelegate(frm1.GetValueA);
td(b);
Close();
}
}
Sunny ChenPosted Jul 2, 2008, 5:20 AM
Getting value from Form2 directly is straightforward. But I think it is better by using events because it reduces the risk of high coupling.
Following is the solution:
Form 1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.OnGetValue += new Form2.GetValueEventHandler(frm2_OnGetValue);
frm2.Show();
}
void frm2_OnGetValue(int val)
{
MessageBox.Show(val.ToString());
}
}
Form2:
public partial class Form2 : Form
{
public delegate void GetValueEventHandler(int val);
public event GetValueEventHandler OnGetValue;
protected void DoGetValue(int val)
{
if (OnGetValue != null)
OnGetValue(val);
}
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int ret = 0;
int.TryParse(textBox1.Text, out ret);
DoGetValue(ret);
Close();
}
}
Aey SaeleePosted Jun 27, 2008, 5:40 AM
Ali ZaidiPosted Jun 26, 2008, 3:49 AM
Just make the textbox modifier to public and then do like:
Form1:
namespace
solutions{
public partial class Form1 : Form{
public Form1(){
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
Form2 ob = new Form2();ob.ShowDialog();
textBox1OnForm1.Text = ob.textBox1OnForm2.Text;
}
}
}
Form2:
namespace
solutions{
public partial class Form2 : Form{
public Form2(){
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
this.Close();}
}
}