c#从form2激活form1上的面板

时间:2017-05-29 23:28:49

标签: c# winforms visual-studio

所以我正在开发一个订购系统,当从form2下订单时,在form1上显示一个带有消息的面板..但它似乎没有用,请帮忙

var url = $"{_salesForceInstance}/services/data/{_salesForceVersion}/query/?q=SELECT+Id,Name,AccountId+from+Contact+WHERE+Email+=+'{email}'";
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.ServicePoint.CloseConnectionGroup(webRequest.ConnectionGroupName);
            webRequest.Method = "GET";
            webRequest.ContentType = "application/json";
            webRequest.Headers.Add("Authorization", $"Bearer {_authorizationToken}");
            var webResponse =  webRequest.GetResponse() as HttpWebResponse;

在此代码之后它应该显示面板但没有任何反应,如果有人可以帮助我请做!谢谢!

2 个答案:

答案 0 :(得分:1)

问题:您的代码无效,因为您创建的form1新实例与您在应用程序中已有的主窗体无关:

Main_Program mp = new Main_Program(); // here

解决方案:您应该使用已经打开的form1。事件很容易做到。在form2上创建一个事件:

public event EventHandler OrderPlaced;

在下订单时提高它:

int chkComm1 = comm1.ExecuteNonQuery();

if(chkComm1 == 1)
{
    OrderPlaced?.Invoke(this, EventArgs.Empty);
}

在form1上订阅form2的事件:

form2.OrderPlaced += Form2_OrderPlaced;

在事件处理程序中激活面板:

private void Form2_OrderPlaced(object sender, EventArgs e)
{
    orderALERT.Enabled = true;
    orderALERT.Visible = true;
}

答案 1 :(得分:0)

将Main_Program的实例传递给Form2的Show()方法,如下所示:

public partial class Main_Program : Form
{
    public Main_Program()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.Show(this); // pass in THIS instance of Main_Program as the "Owner"
    }

}

现在,在Form2中,您可以将Owner强制转换为Main_Program并进行操作。要访问您的" orderALERT"但是,面板必须将其Modifiers属性更改为public:

public partial class Form2 : Form
{

    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (this.Owner != null && this.Owner is Main_Program)
        {
            Main_Program mp = (Main_Program)this.Owner;
            mp.orderALERT.Enabled = true;
            mp.orderALERT.Visible = true;
            mp.orderALERT.Refresh();
        }
    }

}