简体   繁体   English

在不重新打开表单的情况下从另一表单调用一种表单的事件/方法

[英]Calling event/methods of one form from another form without reopening form

'Form1' and 'form2' are open in mdi. “ Form1”和“ form2”在mdi中打开。 when i press button in 'form1' it should call evevt or methods of 'form2', eg like 'checkbox' checked ,refresh grid for that I have code for form2(child form): 当我在“ form1”中按下按钮时,它应该调用evevt或“ form2”的方法,例如,选中“ checkbox”,刷新网格以获取我具有form2(子窗体)的代码:

public partial class Form2: Form
{
    private Form1 Form1_Obj1;
    public Form2(Form1 Form1_Obj2)
    {
        InitializeComponent();
        Form1_Obj1 = Form1_Obj2;
    }
    public Form2()
    {
        InitializeComponent();

    }

for calling events from form1 I have code 从form1调用事件我有代码

Form2 obj=new Form2(this);
obj1.chkSortPlace.Checked = true;
              or         
obj1.chkSortPlace_CheckedChanged(null, null);

problem is event is call but code in event ieassign datasource to gridview is not occur.it will not give error but result is not display grid not refresh 问题是事件被调用,但事件即代码未发生,即未将数据源分配给gridview。它不会给出错误,但结果是未显示网格未刷新

A trick to call a method of some other forms in c#.Net is to use Application.OpenForms here is a sample code 在c#.Net中调用其他形式的方法的技巧是使用Application.OpenForms这里是示例代码

    foreach (Form frm in Application.OpenForms)  
            {  
                if (frm is Form2)
                 {
                     //Put your code here.
                 } 
            }  

Edit: changed the answer because I misunderstood what OP was trying to do. 编辑:更改答案,因为我误解了OP试图做的事情。

The reason you are unable to manipulate chkSortPlace is because by default all controls that you add to a form are marked as private . 您无法操作chkSortPlace的原因是,默认情况下,您添加到表单的所有控件都标记为private

Go to Form1, right click on it, select "View Code" and add the following: 转到Form1,右键单击它,选择“查看代码”并添加以下内容:

public bool SortPlaceChecked 
{
    get { return chkSortPlace.Checked; }
    set { chkSortPlace.Checked = value; }
}

Then, when you want to change the state of chkSortPlace from your other form, simply use the public property you added above. 然后,当您想从其他表单更改chkSortPlace的状态时,只需使用上面添加的公共属性即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM