When an item in my Datagrid is updated an e-mail is send to my gmail. This works great!
I would like to make a change. An email may only be sent when [Stock].Amount is updated to 0. Hope anyone can help me.
This is my query:
private void BtnSend_Click(object sender, RoutedEventArgs e)
{
DataRowView o = (DataRowView)g2.SelectedItem;
int id = Convert.ToInt32(o.Row.ItemArray[0]);
int Total = Convert.ToInt32(o.Row.ItemArray[5]);
try
{
const string query = @"UPDATE [Stock] SET [Stock].Amount = @Total WHERE [Stock].Id = @Id;";
using (SqlConnection con = new SqlConnection(connectionstring))
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id;
cmd.Parameters.Add("@Total", SqlDbType.Int).Value = Total;
con.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("update completed successfully");
binddatagrid();
{
SqlCommand second = new SqlCommand($"SELECT COUNT(*) FROM [Stock] WHERE [Stock].Amount = 0;'");
var fromAddress = new MailAddress("FROM-Email", "From Name");
var toAddress = new MailAddress("To-Email", "To Name");
const string fromPassword = "*****";
const string subject = "Test";
const string body = "text";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
MessageBox.Show("E-mail has been sent.", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
catch
{
MessageBox.Show("A field was entered incorrectly. Correct this and try adding the information again.", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
}
CodePudding user response:
You could just return from the method before sending any email if Total is something else than 0:
private void BtnSend_Click(object sender, RoutedEventArgs e)
{
DataRowView o = (DataRowView)g2.SelectedItem;
int id = Convert.ToInt32(o.Row.ItemArray[0]);
int Total = Convert.ToInt32(o.Row.ItemArray[5]);
if (Total != 0) //< --
return;
try
{
//same code as before...
}
catch
{
MessageBox.Show("A field was entered incorrectly. Correct this and try adding the information again.", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
