Access Of Public Method Between Forms

2020-01-31 11:50发布

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?

4条回答
对你真心纯属浪费
2楼-- · 2020-01-31 12:35

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.

1 - Pass Form1 to Form2

The first thing you can do is to simply pass the existing Form1 to Form2 so that Form2 know which Form1 it should update.

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.

2 - Pass a delegate

Instead of passing the whole Form1 to Form2 we can simple pass a delegate to an update method that Form2 can run. This creates less coupling between Form1 and Form2, if you call Form2 from Form3 you can pass in the update method of Form3 instead and Form3 will be updated. The same Form2 can be reused without modification.

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.

查看更多
男人必须洒脱
3楼-- · 2020-01-31 12:38

I would make your amount_sum method a utility method that returns the value, for example:

public static decimal GetTotalFoobarAmount() 
{ // decimal is just a guess here
    // omitted: sql code
    return theAnswer;
}

Then both blocks of code can call this method, for example.

textBox6.Text = YourClass.GetTotalFoobarAmount().ToString();

As a side-benefit, it also reduces coupling between your UI and DB, which is generally considered a good thing. If the query requires values currently from the form, make those parameters in the method. Note also that for returning a single value you might want to look at ExecuteScalar; it isn't going to make a massive difference, but it is more direct than populating a DataTable and looping over the single row.

查看更多
地球回转人心会变
4楼-- · 2020-01-31 12:39

Marc Gravell's answer is probably sufficient, but in general, if you want to call an instance method on a specific instance of a class, you can't just create a new one and call it on that instance. For your example, you need to call the method on the Form1 instance that already exists. The best way to do that is to have a member variable on the Form2 class of type Form1. You can define a constructor or a property on Form2 which takes a value of type Form1 and set the member variable in it. When Form1 creates an instance of Form2, it can call the constructor and pass in this or set the property to this. Then when the button is clicked on Form2, instead of creating a new instance of Form1, it can call the amount_sum() method on the Form1 instance that is already stored.

查看更多
我只想做你的唯一
5楼-- · 2020-01-31 12:43

Also you may use events:

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.ButtonClickAction += f2_ButtonClickAction;
        f2.Show();
    }

    void f2_ButtonClickAction()
    {
        amount_sum();
    }

Form2:

    public Form2()
    {
        InitializeComponent();
    }

    public event Action ButtonClickAction;

    private void button1_Click(object sender, EventArgs e)
    {
        Action a = ButtonClickAction;
        if (a != null)
            a();
        this.Close();
    }
查看更多
登录 后发表回答