简体   繁体   中英

How do I customize MessageBoxButtons.YesNo so that if they click on "Yes" or "No" to show a message box with information

var deliveryTime = sender as MaskedTextBox;

        DateTime now = DateTime.Now; //Current time
        DateTime delTime = DateTime.Parse(deliveryTime.Text);

        if(delTime <= now) 
        {
           
            MessageBox.Show($"Invalid time {delTime.ToShortTimeString()} (Past time)", "Error", MessageBoxButtons.OKCancel,MessageBoxIcon.Error);
        }
        else 
        {
            MessageBox.Show($"The total for your pizza is $" + Cost + " (to be delivered at " + delTime + ") are you sure you want to order?","Order",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
            
        }

If they click on Yes I want to show a message box with information ok, telling them the order is successful, otherwise I want to show them a message box with warning telling them the order was cancelled.

If they click on Yes I want to show a message box with information ok, telling them the order is successful, otherwise I want to show them a message box with warning telling them the order was cancelled.

As already mentioned, the MessageBox.Show return's a DialogResult of which you can use to determine users action.

DialogResult dRlt;

if (delTime <= now)
{
   MessageBox.Show($"Invalid time {delTime.ToShortTimeString()} (Past time)", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}
else
{
   dRlt = MessageBox.Show($"The total for your pizza is $" + Cost + " (to be delivered at " + delTime + ") are you sure you want to order?", "Order", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
   if(dRlt == DialogResult.OK)
   {
      MessageBox.Show("Order Successful", "Order Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
   }
   else
   {
      MessageBox.Show("Order Canceled", "Canceled", MessageBoxButtons.OK, MessageBoxIcon.Warning);
   }
 }

On another note instead of declaring a variable to keep the DialogResult you can check the result and then do what you'd need:

 if (MessageBox.Show($"The total for your pizza is $" + Cost + " (to be delivered at " + delTime + ") are you sure you want to order?", "Order", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
 {
    MessageBox.Show("Order Successful", "Order Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
 }
 else 
 {
    MessageBox.Show("Order Canceled", "Canceled", MessageBoxButtons.OK, MessageBoxIcon.Warning);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM