I am trying to get access to Form1’s public method on another form Form2 as below. I have a textbox6
control on form1 and there is public method to bind it. But I want to bind it by form2 as below.
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
}
public void amount_sum()
{
string connstr = " server=.;initial catalog=maa;uid=mah;pwd=mah";
SqlConnection con = new SqlConnection(connstr);
con.Open();
string sql = " select sum(amount)as amount from method";
SqlDataAdapter dap = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
dap.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
textBox6.Text = Convert.ToString(ds.Tables[0].Rows[i]["amount"]);
}
}
}
Form2
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.amount_sum();
this.Close();
}
The above method-call is wrong. Please suggest how to correct it.
I want to bind Form1’s textBox6
control from Form2's Button_Click
event-handler by calling the public method, and when Form2 is closed, then Form1’s textbox6
should be bound. Is that possible by calling the public method from Form2?
In Form2 you have
Form1 f1 = new Form1();
f1.amount_sum();
This seems to be a common mistake to create a new Form1 when you want to pass the answer back between forms. The new
keyword does just that, it creates a new Form1, calls the method, does not show the form, the original instance of Form1 is unaffected.
I'll show some steps how to fix this.
public class Form2
{
private readonly Form1 _form1;
public Form2(Form1 form1)
{
_form1 = form1;
}
private void button1_Click(object sender, EventArgs e)
{
_form1.amount_sum(); // now this updates the existing form1 instance
this.Close();
}
}
In Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this); // pass this form1 instance to form2
f2.Show();
}
One issue with this is that is creates a strong coupling between Form1 and Form2. If you change something in Form1 it is easy to break Form2 and the other way around.
public class Form2
{
private readonly Action _ammountUpdater;
public Form2(Action ammountUpdater)
{
_ammountUpdater = ammountUpdater;
}
private void button1_Click(object sender, EventArgs e)
{
_ammountUpdater(); // now this updates the existing form1 instance
this.Close();
}
}
In Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this.amount_sum); // pass the update method to form2
f2.Show();
}
Now you can change amount_sum
to private since it is now really an internal affair of Form1.