Question

I have a simple OK/Cancel DialogResult instance within my form:

MessageBox.Show("Number of records affected:" + numberOfRecordsroll + " Please check the data is correct before proceeding:", "Please validate your changes", MessageBoxButtons.OKCancel);

DialogResult dr = new DialogResult();
if (dr == DialogResult.OK)
{
    // CommitTheChanges();
    MessageBox.Show("test", "test");
}
else if (dr == DialogResult.Cancel)
{
    //Do nothing
}

As you can see if the user clicks yes the method CommitTheChanges should be called, however this was not firing. I have since commented it out and placed a test MessageBox.Show(). Again this is not working. What am I doing wrong here?

Était-ce utile?

La solution

You're just creating a new DialogResult and ignoring the click from the dialog. Instead you need to get the DialogResult from the MessageBox

 String msg = "Number of records affected:" + numberOfRecordsroll + " Please check the data is correct before proceeding:";
 DialogResult dr = MessageBox.Show(msg, "Please validate your changes", MessageBoxButtons.OKCancel);

Autres conseils

You've compared the result of dr which is a new instance of DialogResult it has no reference to the current MessageBox.

You need to assign the current message box DialogResult to dr.

DialogResult dr;

dr = MessageBox.Show("Number of records affected:" + numberOfRecordsroll + " Please check the data is correct before proceeding:", "Please validate your changes", MessageBoxButtons.OKCancel);

if (dr == DialogResult.OK)
                    {
                       // CommitTheChanges();
                        MessageBox.Show("test", "test");
                    }

Beware of the new keyword.

When using new as an operator on a reference type you're immediately creating a new object on the heap and the one resulting from the MessageBox is now ripe for collection by the Garbage Collector. In fact, in this case you are not even capturing the DialogResult from the MessageBox.

Something like this will work:

DialogResult dr = MessageBox.Show("Number of records affected:" + numberOfRecordsroll + " Please check the data is correct before proceeding:", "Please validate your changes", MessageBoxButtons.OKCancel);

if (dr == DialogResult.OK)
{
    CommitTheChanges();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top