Home > Mobile >  Data validate before send back from Form2 to Form1
Data validate before send back from Form2 to Form1

Time:12-10

I have 2 forms, Form1 and Form2.

Let's say, in Form1, it display a list of fruits name in ListBox and one ADD button. In Form2, one TextBox to enter fruit name and OK button.

I able to call Form2 from Form1 when ADD button clicked and pass data from Form2 to Form1 when OK button clicked. (OK button > DialogResult property set to "OK")

BUT one problem... when TextBox in Form2 is empty and OK button clicked, it show the message box then close Form2 and proceed in Form1.

How to let Form2 stay open if TextBox is empty although OK button clicked?

Below are the example code:

public partial class Form1 : Form
{
    private void btnAdd_Click(object sender, EventArgs e)
    {
        using (Form2 f2 = new Form2())
        {
            if (f2.ShowDialog() == DialogResult.OK)
            {
                string newFruit = f2.fruit;
                //add newFruit value into Form1 ListBox
            }
        }
    }
}

public partial class Form2 : Form
{        
    public string fruit { get; }
    private void btnOK_Click(object sender, EventArgs e)
    {
        if (txtFruitName.Text != "")
        {
            fruit = txtFruitName.Text;
        }
        else
        {
            MessageBox.Show("Fruit name cannot be empty!");
        }
    }
}

CodePudding user response:

If you set the DialogResult of a button in a form to something other than None, the button will close the form and update its DialogResult automatically. To control the closing behaviour, you have to implement the logic by yourself - which is really no big thing in this case. Just add the following lines to your Form2 button code and switch the DialogResult of the button in the properties to None.

private void button1_Click(object sender, EventArgs e)
    {
      if (txtFruitName.Text != "")
      {
        fruit = txtFruitName.Text;
        DialogResult = DialogResult.OK;
        Close();
      }
      else
      {
        MessageBox.Show("Fruit name cannot be empty!");
      }

    }

CodePudding user response:

I would subscribe FormClosing event, it's a usual practice to make a validation.

public partial class Form2 : Form
{
    public string fruit { get; }

    Form2()
    {
       InitializeComponent();
       FormClosing  = form2_FormClosing;
    }

    private void btnOK_Click(object sender, EventArgs e)
    {
        if (txtFruitName.Text != "")
        {
            fruit = txtFruitName.Text;
            Close();
        }
        else
        {
            MessageBox.Show("Fruit name cannot be empty!");
        }
    }

    private void form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (string.IsNullOrWhiteSpace(txtFruitName?.Text))
        {
           e.Cancel = true;
        }
     }
}
  • Related