Jak zwrócić wartość z formularza w C#?

Mam główny formularz (nazwijmy go frmHireQuote), który jest potomkiem głównego formularza MDI (frmMainMDI), który wyświetla inny formularz (frmportcontact) poprzez ShowDialog () po kliknięciu przycisku.

Gdy użytkownik kliknie 'OK' na frmportcontact, chcę przekazać kilka zmiennych łańcuchowych z powrotem do niektórych pól tekstowych na frmHireQuote.

Zauważ, że może być wiele instancji frmHireQuote, to oczywiście ważne, że wrócę do instancji, która wywołała tę instancję frmportcontact.

Jaka jest najlepsza metoda?

Author: user2864740, 2011-03-08

7 answers

Utwórz kilka publicznych właściwości na swoim podformularzu w ten sposób

public string ReturnValue1 {get;set;} 
public string ReturnValue2 {get;set;}

Następnie ustaw to w swoim podformularzu ok przycisk kliknij handler

private void btnOk_Click(object sender,EventArgs e)
{
    this.ReturnValue1 = "Something";
    this.ReturnValue2 = DateTime.Now.ToString(); //example
    this.DialogResult = DialogResult.OK;
    this.Close();
}

Następnie w formularzu frmhirequote , Po otwarciu formularza podrzędnego

using (var form = new frmImportContact())
{
    var result = form.ShowDialog();
    if (result == DialogResult.OK)
    {
        string val = form.ReturnValue1;            //values preserved after close
        string dateString = form.ReturnValue2;
        //Do something here with these values

        //for example
        this.txtSomething.Text = val;
    }
}

Dodatkowo, jeśli chcesz Anulować z sub-formularza, możesz po prostu dodać Przycisk do formularza i ustawić jego DialogResult na Cancel, a także ustawić CancelButton właściwość formularza do wspomnianego przycisku - spowoduje to usunięcie klucza escape z formularza.

 301
Author: Richard Friend,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-28 16:46:16

Zwykle tworzę statyczną metodę na form/dialog, którą mogę wywołać. Spowoduje to zwrócenie sukcesu (przycisk OK) lub niepowodzenia wraz z wartościami, które należy wypełnić.

 public class ResultFromFrmMain {
     public DialogResult Result { get; set; }
     public string Field1 { get; set; }


 }

I na formularzu:

public static ResultFromFrmMain Execute() {
     using (var f = new frmMain()) {
          var result = new ResultFromFrmMain();
          result.Result = f.ShowDialog();
          if (result.Result == DialogResult.OK) {
             // fill other values
          }
          return result;
     }
}

To call your form;

public void MyEventToCallForm() {
   var result = frmMain.Execute();
   if (result.Result == DialogResult.OK) {
       myTextBox.Text = result.Field1; // or something like that
   }
}
 12
Author: GvS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-27 23:37:44

Znalazłem kolejny mały problem z tym kodem... a przynajmniej było to problematyczne, kiedy próbowałem go wdrożyć.

Przyciski w frmMain nie zwracają zgodnej wartości, używając VS2010 dodałem następujące i wszystko zaczęło działać dobrze.

public static ResultFromFrmMain Execute() {
     using (var f = new frmMain()) {

          f.buttonOK.DialogResult = DialogResult.OK;
          f.buttonCancel.DialogResult = DialogResult.Cancel;

          var result = new ResultFromFrmMain();
          result.Result = f.ShowDialog();

          if (result.Result == DialogResult.OK) {
             // fill other values
          }
          return result;
     }
}

Po dodaniu dwóch wartości przycisków okno dialogowe działało świetnie! Dzięki za przykład, to naprawdę pomogło.

 6
Author: DaveHelton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-16 04:08:51

Właśnie wstawiłem do konstruktora coś przez odniesienie, aby subform mógł zmienić swoją wartość, a main form może uzyskać nowy lub zmodyfikowany obiekt z subform.

 1
Author: SerG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-08 12:18:53

Używam MDI dość dużo, podoba mi się znacznie bardziej (gdzie można go używać) niż wiele form pływających.

Ale aby czerpać z tego co najlepsze, musisz uporać się z własnymi wydarzeniami. To ułatwia Ci życie.

Przykład szkieletu.

Mieć własne typy interupt,

//Clock, Stock and Accoubts represent the actual forms in
//the MDI application. When I have multiple copies of a form
//I also give them an ID, at the time they are created, then
//include that ID in the Args class.
public enum InteruptSource
{
    IS_CLOCK = 0, IS_STOCKS, IS_ACCOUNTS
}
//This particular event type is time based,
//but you can add others to it, such as document
//based.
public enum EVInterupts
{
    CI_NEWDAY = 0, CI_NEWMONTH, CI_NEWYEAR, CI_PAYDAY, CI_STOCKPAYOUT, 
   CI_STOCKIN, DO_NEWEMAIL, DO_SAVETOARCHIVE
}

Wtedy twój własny typ Args

public class ControlArgs
{
    //MDI form source
    public InteruptSource source { get; set; }
    //Interrupt type
    public EVInterupts clockInt { get; set; }
    //in this case only a date is needed
    //but normally I include optional data (as if a C UNION type)
    //the form that responds to the event decides if
    //the data is for it.
    public DateTime date { get; set; }
    //CI_STOCKIN
    public StockClass inStock { get; set; }

}

Następnie użyj delegata w swojej przestrzeni nazw, ale poza klasą

namespace MyApplication
{
public delegate void StoreHandler(object sender, ControlArgs e);
  public partial class Form1 : Form
{
  //your main form
}

Teraz albo ręcznie lub za pomocą GUI, mieć MDIparent odpowiada na wydarzenia form dziecka.

Ale za pomocą owr Args, możesz zredukować to do jednej funkcji. i możesz mieć przepis do interupt interupt, dobry do debugowania, ale może być przydatny również w inny sposób.

Wystarczy, że wszystkie kody zdarzeń mdiparent wskazują na jedną funkcję,

        calendar.Friday += new StoreHandler(MyEvents);
        calendar.Saturday += new StoreHandler(MyEvents);
        calendar.Sunday += new StoreHandler(MyEvents);
        calendar.PayDay += new StoreHandler(MyEvents);
        calendar.NewYear += new StoreHandler(MyEvents);

Prosty mechanizm przełączania zwykle wystarcza, aby przekazać zdarzenia do odpowiednich form.

 0
Author: Bob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-08 13:25:21

Jeśli chcesz przekazać dane do form2 z form1 bez przekazywania jak nowe form(sting "data");

Zrób tak w formie 1

using (Form2 form2= new Form2())
{
   form2.ReturnValue1 = "lalala";
   form2.ShowDialog();
}

W formularzu 2 Dodaj

public string ReturnValue1 { get; set; }

private void form2_Load(object sender, EventArgs e)
{
   MessageBox.Show(ReturnValue1);
}

Możesz również użyć wartości w form1 w ten sposób, jeśli chcesz zamienić coś w form1

Tylko w form1

textbox.Text =form2.ReturnValue1
 0
Author: Matas Lesinskas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:22:30

Najpierw musisz zdefiniować atrybut w form2 (dziecko) zaktualizujesz ten atrybut w form2, a także z form1 (rodzic):

 public string Response { get; set; }

 private void OkButton_Click(object sender, EventArgs e)
 {
    Response = "ok";
 }

 private void CancelButton_Click(object sender, EventArgs e)
 {
    Response = "Cancel";
 }

Wywołanie form2 (dziecka) z form1 (rodzica):

  using (Form2 formObject= new Form2() )
  {
     formObject.ShowDialog();

      string result = formObject.Response; 
      //to update response of form2 after saving in result
      formObject.Response="";

      // do what ever with result...
      MessageBox.Show("Response from form2: "+result); 
  }
 0
Author: Wajid khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-11 19:02:32