I have a dataGridView that is filled by means of a stored procedure, and a timer that reloads the table every 5 seconds so that it shows me the added rows in real time, that is, every time something is inserted in the table in sql server it shows me in the dataGridView, what I need is to send an email every time a data is added, that is, every time there is an insert, how can I send it and how can I optimize the Refresh of the table to remove the timer
using System;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Net.Mail;
using System.Timers;
using System.Windows.Forms;
namespace AlertaPDC
{
public partial class Form1 : Form
{
private static System.Timers.Timer aTimer;
private SqlCommand Comando = new SqlCommand();
private SqlDataReader LeerFilas;
public Form1()
{
InitializeComponent();
ListarTraslados();
SetTimer();
}
private SqlConnection Connection()
{
return new SqlConnection("Server=192.168.1.; Password=S0p0rt3;user=sa;DataBase=PRU");
}
public DataTable ListarPDC()
{
SqlConnection conexion = Connection();
DataTable Tabla = new DataTable();
conexion.Open();
Comando.Connection = conexion;
Comando.CommandText = "SP_ALERTAPDC";
Comando.CommandType = CommandType.StoredProcedure;
LeerFilas = Comando.ExecuteReader();
Tabla.Load(LeerFilas);
LeerFilas.Close();
conexion.Close();
return Tabla;
}
public void ListarTraslados()
{
dataGridView1.DataSource = ListarPDC();
}
private void SetTimer()
{
aTimer = new System.Timers.Timer(5000);
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Invoke((MethodInvoker)ListarTraslados);
}
private void Envio()
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
MailMessage message = new MailMessage("[email protected]", "[email protected]", "RESOLUCION DE FACTURACION CREDITO PROXIMA A VENCER", "La resolucion de facturacion de el punto de venta X, Consecutivos restantes: " + resolucionFa);
//Si tu servidor smtp necesita credenciales, las pones asi
client.EnableSsl = true;
client.Credentials = new NetworkCredential("[email protected]", "Sopor19*");
//Finalmente envias el mensaje
client.Send(message);
}
}
}
Basically you need to control 2 things: When you open the form and when you fill the datagridView. And for this, I have created 2 variables at the form level called
cargaInicial
(by default, false) andregistrosActuales
, which will be responsible for saving the records that we currently have in the datagridView.Therefore:
cargaInicial
will take care of not sending an email when we are opening the form, since we are filling the datagridView for the first time.registrosActuales
controls the number of current records in the datagridView. If it changes and is less than the records that come from the BBDD, we will send an email and assign the new value. In this way, the next time the timer is triggered, if there is no news, it will not send any mail.