使用表单2从表单1运行空白

时间:2015-09-04 08:52:58

标签: c#

我试图从Form2执行Void并更新Form1我尝试在按钮单击和Form_Close上添加它,也在Form1_Activated,Form1_Enter上添加它但仍然没有进展

这就是我尝试过的事情:(但是没有运气让它发挥作用......

Form1.cs的

public void LoadTable()
{
   //Code to Populate Datagridview
   string sql = "";
   SqlConnection Connection = new SqlConnection(Global.Connection);
   SqlCommand CMD = new SqlCommand(sql, Connection);

   SqlDataAdapter DA = new SqlDataAdapter();
   DA.SelectCommand = CMD;

   DataSet DS = new DataSet();
   DA.Fill(DS);

   ApplicantsGrid.DataSource = DS.Tables[0].DefaultView;
}
private void Form1Button_Click(object sender, EventArgs e)
{
    Form2 Form2 = new Form2();
    Form2.showDialog();
}

Form2.cs

private void Form2Button_Click(object sender, EventArgs e)
{
      Form1 Form1 = new Form1();
      Form1.LoadTable();
}

这是我制作的节目的主要问题:(

2 个答案:

答案 0 :(得分:1)

我非常肯定,你做的是你想做的其他事情。

您正在LoadTable的新实例上调用Form1。您可能想要的是按照Sayse的建议在现有表单上调用它。

您可能想在现有实例上调用它。你可能会这样做,例如:

Form1 Button_Click代码:

class Form1
{
    public static Form1 Instance {get; private set;}

    public Form1()
    {
        Instance = this;
        //InitializeComponents and what ever else.
    }

    public void LoadTable()
    {
        //implementation
    }
}

Form2代码:

private void Button_Click(object sender, EventArgs e)
{
    if (Form1.Instance != null) //must be careful about this.
    {
        Form1.Instance.LoadTable(); //like this you will call the method on the existing instance of the form.
    }
}

答案 1 :(得分:0)

 public partial class Form1 : Form
    {
        internal static Form1 ViewForm1; // Make other form run Public void from Form1

        public form1()
        {
            InitializeComponent();
            ViewForm1 = this;  //Add this
        }
        public void DoSomething()
        {
          //Code here...
        }
}   


 public partial class Form1 : Form
    {
        public form2()
        {
            InitializeComponent();            
            Form1.ViewForm1.ShowData(); // Call public void from form1
        }
    }



     public partial class Form1 : Form
        {
            internal static Form1 ViewForm1; // Make other form run Public void from Form1

            public form1()
            {
                InitializeComponent();
                ViewForm1 = this;  //Add this
            }
            public void DoSomething()
            {
              //Code here...
            }
    }	
	

     public partial class Form1 : Form
        {
            public form2()
            {
                InitializeComponent();            
                Form1.ViewForm1.ShowData(); // Call public void from form1
            }
		}