简体   繁体   中英

How do I pass a bool variable from form2 back to form1?

我正在尝试从表格2传递布尔变量并将其放入表格1。您将如何做?

1 , By instance parameter

  bool flg = false;
  form1 f1 = new form1(flg);
  f1.show();

2, By the public property.

  form1 f1 = new form1();
  f1.FLG = false;
  f1.show();

3, By the public set method

  form1 f1 = new form1();
  f1.SetFlg(false);
  f1.show();

You need to write public property/method to return (exchange) data between forms. First of all you need to understand - How to access properties/methods of an object of one class from the methods/properties of an object of another class?

For instance, create a public property say Status in Form2 class,

public partial class Form2
{
  ...
  private bool _status; 
  public bool Status
   {
    get
     {
      return _status;
     }
    set
    {
      _status=value;
     }
   }
  ....
}

Now, if you want to get the value of Status property from within the Form1 method.

public partial class Form1
{
   ....
   protected void Button1_Click(object sender, EventArgs e)
   {
    Form2 frm=new Form2();
    frm.ShowDialog();
    bool status=frm.Status;
   }
}

Try this :

Form 1:

//Create global variable
public bool test;
//Initialize the form
Form2 f2 = new Form2(this);
f2.ShowDialog();

Form 2:

Form1 originalForm;
public Form2(Form1 incomingForm)
{
    originalForm = incomingForm;
    InitializeComponent();
}

Set or get like this: originalForm.test

Hope it works

I'd use an interface.

 public interface IForm
 {
    bool GetResult();
 }
 // form 2
 public partial class Form2 : Form, IForm (...)
 private bool Result;
 public bool GetResult()
 {
  return Result;
 }

 // form 1
 var form2 = new Form2();
 ((IForm)form2).GetResult();
//In Form1 define global static bool variable
Form1
{ 

public static bool variable;

}

// In Form2 call it
Form2
{
   Form1.variable = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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