MessageBox没有提供预期的DialogResult

时间:2013-06-24 10:35:31

标签: c# .net winforms dialogresult

我的表单中有一个简单的OK / Cancel DialogResult实例:

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
}

正如您所看到的,如果用户单击是,则应调用方法CommitTheChanges,但这并未触发。我已将其评论出来并进行了测试MessageBox.Show()。再次这不起作用。我在这里做错了什么?

3 个答案:

答案 0 :(得分:7)

您只是创建一个新的DialogResult并忽略对话框中的单击。相反,你需要从MessageBox

获取DialogResult
 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);

答案 1 :(得分:0)

您已对dr的结果进行了比较,DialogResultMessageBox的新实例,但它没有引用当前的DialogResult

您需要将当前消息框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"); } 分配给博士

{{1}}

答案 2 :(得分:0)

小心new关键字。

new上使用reference type作为运算符时,您会立即在堆上创建一个新对象,而MessageBox生成的对象现在已成熟,可供垃圾收集集电极。事实上,在这种情况下,您甚至无法从DialogResult抓取MessageBox

这样的事情会起作用:

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();
}