Editar registros en MySQL (MariaDB) con C# [06]
En este tutorial vamos a editar registros en MySQL (MariaDB) con C# en base a los diferentes campos que creamos.
Estaremos a la escucha del evento CellClick osea cuando se le de click a una celda realizaremos los siguiente.
Leeremos la posición del registro.
En base a la posición del registro llenaremos los campos nombre, puesto y edad.
Insertamos un botón llamado Editar que al dar click actualizará los datos del registro seleccionado pero en este caso usando el id.
Codigo: https://github.com/programadornovato/MySQL-CSharp/commit/78fba9c470618cce7a5ae29c5b7ecd1542013559
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace MySQL_CSharp
{
public partial class Form1 : Form
{
MySqlConnection myCon;
string idSel = "";
public Form1()
{
InitializeComponent();
conectar();
llenarTabla();
}
private void conectar() {
try
{
string server = "localhost";
string database = "empleados";
string user = "root";
string pwd = "123456";
string cadenaConexion = "server=" + server + ";database=" + database + ";" + "Uid=" + user + ";pwd=" + pwd + ";";
myCon = new MySqlConnection(cadenaConexion);
myCon.Open();
lblResultado.Text = "Conexion exitosa";
}
catch (Exception error)
{
lblResultado.Text = "Error de conexion " + error;
}
}
private void llenarTabla() {
string query = "select id,nombre,puesto,edad from trabajadores;";
MySqlCommand comandoDB = new MySqlCommand(query, myCon);
comandoDB.CommandTimeout = 60;
MySqlDataReader reader;
try
{
reader = comandoDB.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
int n = dgTrabajadores.Rows.Add();
dgTrabajadores.Rows[n].Cells[0].Value = reader.GetString(0);
dgTrabajadores.Rows[n].Cells[1].Value = reader.GetString(1);
dgTrabajadores.Rows[n].Cells[2].Value = reader.GetString(2);
dgTrabajadores.Rows[n].Cells[3].Value = reader.GetString(3);
//MessageBox.Show(reader.GetString(0));
}
}
else
{
Console.WriteLine("No hay trabajadores");
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void btnBuscar_Click(object sender, EventArgs e)
{
string where = " where 1=1 ";
//Si el nombre no esta vacio
if (txtBusNombre.Text != "")
{
where = where + " and nombre like'%" + txtBusNombre.Text + "%' ";
}
//Si el puesto no esta vacio
if (txtBusPuesto.Text != "")
{
where = where + " and puesto like'%" + txtBusPuesto.Text + "%' ";
}
//Si la edad no esta vacio
if (txtBusEdad.Text != "")
{
where = where + " and edad like'%" + txtBusEdad.Text + "%' ";
}
string query = "select id,nombre,puesto,edad from trabajadores " + where + " ;";
MySqlCommand comandoDB = new MySqlCommand(query, myCon);
comandoDB.CommandTimeout = 60;
MySqlDataReader reader;
dgTrabajadores.Rows.Clear();
dgTrabajadores.Refresh();
try
{
reader = comandoDB.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
int n = dgTrabajadores.Rows.Add();
dgTrabajadores.Rows[n].Cells[0].Value = reader.GetString(0);
dgTrabajadores.Rows[n].Cells[1].Value = reader.GetString(1);
dgTrabajadores.Rows[n].Cells[2].Value = reader.GetString(2);
dgTrabajadores.Rows[n].Cells[3].Value = reader.GetString(3);
//MessageBox.Show(reader.GetString(0));
}
}
else
{
Console.WriteLine("No hay trabajadores");
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void btnInsertar_Click(object sender, EventArgs e)
{
string query = "";
string mensajeError = "";
if (txtInNombre.Text == "") {
mensajeError = mensajeError + "El nombre no puede estar vacio";
}
if (txtInPuesto.Text == "") {
mensajeError = mensajeError + "El puesto no puede estar vacio";
}
if (txtInEdad.Text == "") {
mensajeError = mensajeError + "La edad no puede estar vacio";
}
if (mensajeError == "")
{
query = "insert into trabajadores " +
"(nombre ,puesto ,edad) values " +
"('" + txtInNombre.Text + "','" + txtInPuesto.Text + "','" + txtInEdad.Text + "')";
MySqlCommand comando = new MySqlCommand(query, myCon);
comando.CommandTimeout = 60;
MySqlDataReader reader;
try
{
reader = comando.ExecuteReader();
reader.Close();
dgTrabajadores.Rows.Clear();
dgTrabajadores.Refresh();
llenarTabla();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
else {
MessageBox.Show(mensajeError);
}
}
private void dgTrabajadores_CellClick(object sender, DataGridViewCellEventArgs e)
{
int sel = e.RowIndex;
txtInNombre.Text = dgTrabajadores.Rows[sel].Cells[1].Value.ToString();
txtInPuesto.Text = dgTrabajadores.Rows[sel].Cells[2].Value.ToString();
txtInEdad.Text = dgTrabajadores.Rows[sel].Cells[3].Value.ToString();
idSel = dgTrabajadores.Rows[sel].Cells[0].Value.ToString();
}
private void btnEditar_Click(object sender, EventArgs e)
{
string query = "";
string mensajeError = "";
if (txtInNombre.Text == "")
{
mensajeError = mensajeError + "El nombre no puede estar vacio";
}
if (txtInPuesto.Text == "")
{
mensajeError = mensajeError + "El puesto no puede estar vacio";
}
if (txtInEdad.Text == "")
{
mensajeError = mensajeError + "La edad no puede estar vacio";
}
if (mensajeError == "")
{
query = "update trabajadores set " +
"nombre='"+txtInNombre.Text+"'," +
"puesto='"+txtInPuesto.Text + "',"+
"edad='"+txtInEdad.Text + "' " +
"where id='"+idSel+"'; ";
MySqlCommand comando = new MySqlCommand(query, myCon);
comando.CommandTimeout = 60;
MySqlDataReader reader;
try
{
reader = comando.ExecuteReader();
reader.Close();
dgTrabajadores.Rows.Clear();
dgTrabajadores.Refresh();
llenarTabla();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
else
{
MessageBox.Show(mensajeError);
}
}
}
}
🎦 [CURSO] C##️⃣: https://www.youtube.com/watch?v=NKPMGY6NCko&list=PLCTD_CpMeEKQSOU8Vf9VHXrZa2rc8X0X5&index=1&t=3s&ab_channel=programadornovatoprogramadornovato
🎦 [CURSO] C CON FORMULARIOS##️⃣: https://www.youtube.com/watch?v=l0_U4oyOuns&list=PLCTD_CpMeEKTBih1VgeunCjc83ZQ6UBMI&index=1&ab_channel=programadornovatoprogramadornovato
🎦 [CURSO] C++ DE 0 A HEROE 🦸: https://www.youtube.com/watch?v=APN8aCyPvww&list=PLCTD_CpMeEKTofxs7iottRxJ5YPM7BOcc&ab_channel=programadornovato
🎦 [Curso] Java Netbeans GUI Completo☕: https://www.youtube.com/watch?v=18UA7X2ss8g&list=PLCTD_CpMeEKThfXo8D-RXOGu5FarO7_qv&ab_channel=programadornovato
Anterior tutorial Siguiente tutorial