How to pass a List object from a dialogbox

2019-08-23 19:10发布

I call a form with ShowDialog() from my main form. Instead of passing values one by one from the dialog form, I'd like to pass a list of the values, so that the main form can work with them (depending on the options on the main form, the number of fields on the dialog form differs).

This code, however, crashes my program, but does not throw any exceptions. The problem must be with the list, because this method worked with simple variables.

The dialog form's class contains this:

List<string> valuesToReturn;
public List<string> ValuesToReturn { get => ValuesToReturn; set => ValuesToReturn = value; }

The dialog form's constructor creates a new instance of the list:

valuesToReturn = new List<string>();

And then in the event handler (when Enter is pressed) I would like to add the values of all the NoEnterTextBox-es to the list:

foreach (object item in this.Controls)
{
    if(item is NoEnterTextBox) {
        valuesToReturn.Add((item as NoEnterTextBox).Text);
    }
}

Please help me how to correct this code. Thank you.

标签: c# winforms
1条回答
时光不老,我们不散
2楼-- · 2019-08-23 19:49

use the DialogResult value of form 2 in order to determine if there is a need to refresh Form1. also HandleList() method will populate all text boxes .text to the list.

calling Form2 from Form1:

 private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            if (f2.ShowDialog() == DialogResult.OK)

            {
                // refresh form
               AddItemsFromListInForm2(f2.valuesToReturn);
            } 
        }

 private void AddItemsFromListInForm2(List<string> valuesToReturn)
 {
     // do something with valuesToReturn...
 }   

user presses (OK \ Save) button on form2:

  private void button1_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            HandleList();
            this.Close();
        }

   private void HandleList()
   {

        foreach (Control c in this.Controls)
        {
            if(c is TextBox)
            {
                valuesToReturn.Add(c.Text);
            }
        }
   }       

in another button on Form2 you can do that piece of code, if there is a case that you dont want to refresh Form1:

 private void button2_Click(object sender, EventArgs e)
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
查看更多
登录 后发表回答