ArtR45
ArtR45

Reputation: 39

C# DialogResult with error check

I'm having a strange problem ... I have two forms (Form1 & Form2). Form1 calls with an old name (string) and the user enters a new name (textbox1) in Form2 which is returned to Form1. Everything works fine if they enter a value or cancel ... however I want to put an error check to insure they enter a value, among other things. The error check works fine, but after the error, when a correct value is entered, form2 closes but nothing happens. I put in some breakpoints and Form1 seems to hold on the using(form2 ...) statement, waiting for Form2 to finish, but after firing the error message, nothing happens. If I remove the ... Form2 F2 = new Form2 ... Form2 just closes and returns to Fomr1. Ideally I'd like to stay on Form2 until a value gets entered or the user cancels. What am I missing?

// Form1 
using(Form2 F5 = new Form2(SelNm))
{
    if(F5.ShowDialog()== DialogResult.OK)
    {
        //Do stuff
    }
}

// Form2
public string newName { get; set; }
public string oldName { get; set; }

public Form2(string oldNm)
{
    InitializeComponent();
    oldName = oldNm;      
}

private void btnOK_Click(object sender, EventArgs e)
{
    if (textbox1.Text.Length > 0)
    {
        newName = textbox1.Text;
        DialogResult = DialogResult.OK;
        Close();
    }
    else
    {
        MessageBox.Show("ERROR: Must enter a new name.");
        DialogResult = DialogResult.Cancel;
        Form2 f2 = new Form2(oldName);
        f2.Show();
        Close();
    }
}

Upvotes: 0

Views: 678

Answers (1)

jegtugado
jegtugado

Reputation: 5141

The reason for this is that you called a new Form2 after the error dialog is shown. This is not the instance of the Form2 which Form1 is waiting for. Instead of calling a new Form2 why not re-use the current Form2?

Instead of this:

    MessageBox.Show("ERROR: Must enter a new name.");
    DialogResult = DialogResult.Cancel;
    Form2 f2 = new Form2(oldName);
    f2.Show();
    Close();

Why not this?

    MessageBox.Show("ERROR: Must enter a new name.");
    // Do not close the form so the user can
    // input again

Update:

As suggested on the comments..

private void textbox1_TextChanged(object sender, RoutedEventArgs e)
{
    btnOK.Enabled = !string.IsNullOrWhiteSpace(textbox1.Text);
}

Upvotes: 2

Related Questions