Home > database >  How do I customize MessageBoxButtons.YesNo so that if they click on "Yes" or "No"
How do I customize MessageBoxButtons.YesNo so that if they click on "Yes" or "No"

Time:10-29

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.

CodePudding user response:

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);
 }
  •  Tags:  
  • c#
  • Related