Comencemos con los requisitos:
Requisitos para el Desarrollos
- IDE (Visual Studio 2010).
- SGBD (SQL Server 2008).
- LP (C#).
- Crear la solución con nombre de [ADO.Net Mantenimiento] así mismo creamos el proyecto que se llamara como el mismo nombre que tiene la solución.
- Crear la base de datos y la tabla (ambos objetos son la misma base de datos y tabla que se uso en la publicación sobre ADO.Net - Recuperar datos con DataReader)
- Diseñamos nuestro formulario que esta compuesto por los controles de etiqueta (label), texto (textbox), grillas (datagridview) y botones (button).
Breves Explicaciones
Cadena de conexión (app.config).
Crear nuestra cadena de conexión (código XML), con nombre "cndb"
<configuration>
<configsections>
</configsections>
<connectionstrings>
<add connectionstring="Data Source=local;Initial Catalog=dbAdoNet;Integrated Security=True" name="cndb" providername="System.Data.SqlClient">
</add></connectionstrings>
</configuration>
Entidades
(clsClienteEntity).
Creamos la
clase de entidad, donde creamos las propiedades (columna) de la entidad (tabla
cliente).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ADO.Net_Mantenimiento
{
public class ClsClienteEntity
{
public int IdCliente {get; set;}
public string NomCliente {get; set;}
public string ApeCliente{get; set;}
public string DirCliente {get; set;}
public string TelCliente {get;set;}
public string CelCliente { get; set;}
}
}
Creamos nuestro método privado cargarCliente, en la cual creamos nuestra estructura de solo lectura y hacemos referencia a nuestra clase de entidades ClsClienteEntity.
//Invocamos o importamos estas referencias
using System.Data;
using System.Data.SqlClient; // Proveedor de base de datos
using System.Configuration; // para poder acceder a nuestra archivo de configuraciones (App.config)
//Sobre esta evento ya se hablo en el anterior articulo
public class ClsClienteDAL
{
private static ClsClienteEntity CargaCliente(IDataReader Reader)
{
ClsClienteEntity cliente = new ClsClienteEntity();
cliente.IdCliente = Convert.ToInt32(Reader["IdCliente"]);
cliente.NomCliente = Convert.ToString(Reader["NomCliente"]);
cliente.ApeCliente = Convert.ToString(Reader["ApeCliente"]);
cliente.DirCliente = Convert.ToString(Reader["DirCliente"]);
cliente.TelCliente = Convert.ToString(Reader["TelCliente"]);
cliente.CelCliente = Convert.ToString(Reader["CelCliente"]);
return cliente;
}
//Filtrar todos los registros de la entidad cliente
public static List<clsclienteentity> ClienteAll()
{
string strsql = @"SELECT [IdCliente]
,[NomCliente]
,[ApeCliente]
,[DirCliente]
,[TelCliente]
,[CelCliente]
FROM [dbAdoNet].[dbo].[Cliente]";
List<clsclienteentity> listar = new List<clsclienteentity>();
using (SqlConnection sqlcn = new SqlConnection(ConfigurationManager.ConnectionStrings["cndb"].ToString()))
{
SqlCommand sqlcmd = new SqlCommand(strsql, sqlcn);
sqlcn.Open();
SqlDataReader sqlReader = sqlcmd.ExecuteReader();
while (sqlReader.Read())
{
listar.Add(CargaCliente(sqlReader));
}
return listar;
}
}
//Filtrar registro por ID de la entidad cliente
public static ClsClienteEntity ClienteID(int ID)
{
string strsql = @"SELECT [IdCliente]
,[NomCliente]
,[ApeCliente]
,[DirCliente]
,[TelCliente]
,[CelCliente]
FROM [dbAdoNet].[dbo].[Cliente]
WHERE [IdCliente]=@ID";
ClsClienteEntity cliente = null;
using (SqlConnection sqlcn = new SqlConnection(ConfigurationManager.ConnectionStrings["cndb"].ToString()))
{
SqlCommand sqlcmd = new SqlCommand(strsql, sqlcn);
sqlcmd.Parameters.AddWithValue("Id", ID);
sqlcn.Open();
SqlDataReader sqlReader = sqlcmd.ExecuteReader();
if (sqlReader.Read())
{
cliente = CargaCliente(sqlReader);
}
return cliente;
}
}
//Capturar el máximo ID de la entidad cliente (tabla)
private static int idmax()
{
string strsql = @"SELECT MAX(IdCliente) FROM CLIENTE";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cndb"].ToString()))
{
SqlCommand cmdsql = new SqlCommand(strsql, cn);
cn.Open();
return Convert.ToInt32(cmdsql.ExecuteScalar());
}
}
//Método Insertar nuevo registro
public static ClsClienteEntity InsertarRegistro(ClsClienteEntity cliente)
{
string strsql = @"INSERT INTO dbAdoNet.dbo.Cliente
(IdCliente
,NomCliente
,ApeCliente
,DirCliente
,TelCliente
,CelCliente)
VALUES
(@IdCliente
,@NomCliente
,@ApeCliente
,@DirCliente
,@TelCliente
,@CelCliente)";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cndb"].ToString()))
{
//Incrementamos nuevo id
int nuevoid = idmax() + 1;
SqlCommand cmdsql = new SqlCommand(strsql, cn);
cmdsql.Parameters.AddWithValue("IdCliente", nuevoid);
cmdsql.Parameters.AddWithValue("NomCliente", cliente.NomCliente);
cmdsql.Parameters.AddWithValue("ApeCliente", cliente.ApeCliente);
cmdsql.Parameters.AddWithValue("DirCliente", string.IsNullOrEmpty(cliente.DirCliente) ? (object)DBNull.Value : cliente.DirCliente);
cmdsql.Parameters.AddWithValue("TelCliente", cliente.TelCliente);
cmdsql.Parameters.AddWithValue("CelCliente", string.IsNullOrEmpty(cliente.CelCliente) ? (object)DBNull.Value : cliente.CelCliente);
cn.Open();
cmdsql.ExecuteNonQuery();
cliente.IdCliente = nuevoid;
return cliente;
}
}
//Método Actualizar registro
public static ClsClienteEntity ActualizarRegistro(ClsClienteEntity cliente, int id)
{
//int idcli = Convert.ToInt32(cliente.IdCliente);
string strsql = @"UPDATE dbAdoNet.dbo.Cliente
SET NomCliente = @NomCliente
,ApeCliente = @ApeCliente
,DirCliente = @DirCliente
,TelCliente = @TelCliente
,CelCliente = @CelCliente
WHERE IdCliente = @IdCliente";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cndb"].ToString()))
{
SqlCommand cmdsql = new SqlCommand(strsql, cn);
cmdsql.Parameters.AddWithValue("NomCliente", cliente.NomCliente);
cmdsql.Parameters.AddWithValue("ApeCliente", cliente.ApeCliente);
cmdsql.Parameters.AddWithValue("DirCliente", string.IsNullOrEmpty(cliente.DirCliente)?(object)DBNull.Value:cliente.DirCliente);
cmdsql.Parameters.AddWithValue("TelCliente", cliente.TelCliente);
cmdsql.Parameters.AddWithValue("CelCliente", string.IsNullOrEmpty(cliente.CelCliente) ? (object)DBNull.Value : cliente.CelCliente);
cmdsql.Parameters.AddWithValue("IdCliente", id);
cn.Open();
cmdsql.ExecuteNonQuery();
return cliente;
}
}
public static void ElimarRegistro(int id)
{
string strsql = @"DELETE FROM Cliente WHERE IdCliente = @IdCliente";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cndb"].ToString()))
{
SqlCommand cmdsql = new SqlCommand(strsql, cn);
cmdsql.Parameters.AddWithValue("IdCliente", id);
cn.Open();
cmdsql.ExecuteNonQuery();
}
}
En el
formulario invocaremos nuestros eventos que se crearon en la clsClienteDal.
Iniciamos
controlando nuestro formulario en el evento cargar (load); controlamos
nuestra caja de texto de solo lectura (este valor es el código autogenerado) y
a su vez cargamos nuestra grilla invocando nuestra clase ClsClienteDAL y
evento ClienteAll().
En el evento doble clic de la grilla validamos si es que existe if (row != null) registros y capturamos el registro “ID” (int id = Convert.ToInt32(row.Cells["ID"].Value); que se encuentra en la grilla; si es que todo marcha bien seleccionamos las entidades (if (this.ClienteSelected != null) para setear los valores en los controles, que en te caso todos son cajas de textos.
Evento para realizar el limpiado de las cajas texto y enviar el foco a la caja de texto (txtNombres.Focus()).
Evento clic de botón guardar, recuperamos y validamos los valores obligatorios a ingresar en la caja de texto e invocamos los eventos de Inserción y actualización que se encuentra en la clase ClsClienteDAL, limpiamos los controles ingresados y por último invocamos al evento ClienteAll que se encuentra en la clase ClsClienteDAL.
Evento clic de botón eliminar, capturamos el id e invocamos el evento ElimarRegistro(id).
//Evento Load
private void Form1_Load(object sender, EventArgs e)
{
//Bloquear campo id (sera autogenerado)
txtID.ReadOnly = true;
//Cargamos el datagridview
dgv_cliente.DataSource = ClsClienteDAL.ClienteAll();
}
En el evento doble clic de la grilla validamos si es que existe if (row != null) registros y capturamos el registro “ID” (int id = Convert.ToInt32(row.Cells["ID"].Value); que se encuentra en la grilla; si es que todo marcha bien seleccionamos las entidades (if (this.ClienteSelected != null) para setear los valores en los controles, que en te caso todos son cajas de textos.
//Cargar los textbox desde el datagridview
private void dgv_cliente_DoubleClick(object sender, EventArgs e)
{
DataGridViewRow row = dgv_cliente.CurrentRow as DataGridViewRow;
if (row != null)
{
//Obtenemos la columna ID del datagridview
int id = Convert.ToInt32(row.Cells["ID"].Value);
this.ClienteSelected = ClsClienteDAL.ClienteID(id);
if (this.ClienteSelected != null)
{
ClsClienteEntity cliente = this.ClienteSelected;
txtID.Text = Convert.ToString(cliente.IdCliente);
txtNombres.Text = cliente.NomCliente;
txtApellidos.Text = cliente.ApeCliente;
txtDireccion.Text = cliente.DirCliente;
txtTelefono.Text = cliente.TelCliente;
txtCelular.Text = cliente.CelCliente;
}
}
}
Evento para realizar el limpiado de las cajas texto y enviar el foco a la caja de texto (txtNombres.Focus()).
//Metodo Limpiar controles
private void LimpiarCtrl()
{
txtID.Text = "";
txtNombres.Text = "";
txtApellidos.Text = "";
txtDireccion.Text = "";
txtTelefono.Text = "";
txtCelular.Text = "";
txtNombres.Focus();
}
Evento clic de botón guardar, recuperamos y validamos los valores obligatorios a ingresar en la caja de texto e invocamos los eventos de Inserción y actualización que se encuentra en la clase ClsClienteDAL, limpiamos los controles ingresados y por último invocamos al evento ClienteAll que se encuentra en la clase ClsClienteDAL.
private void btnGuardar_Click(object sender, EventArgs e)
{
try
{
ClsClienteEntity cliente = new ClsClienteEntity();
//Recuperar los valores ingresados de la caja de texto
cliente.NomCliente = txtNombres.Text;
cliente.ApeCliente = txtApellidos.Text;
cliente.DirCliente = txtDireccion.Text;
cliente.TelCliente = txtTelefono.Text;
cliente.CelCliente = txtCelular.Text;
//Validación - Datos obligaatorios a ingresar
if (txtNombres.Text == "")
{
MessageBox.Show("Falta Ingresar Nombre", "Aviso del Sistema", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtNombres.Focus();
return;
}
if (txtApellidos.Text == "")
{
MessageBox.Show("Falta Ingresar Apellidos", "Aviso del Sistema", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtApellidos.Focus();
return;
}
if (txtTelefono.Text == "")
{
MessageBox.Show("Falta Ingresar Telefono", "Aviso del Sistema", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtTelefono.Focus();
return;
}
// Si es que la caja de texto se encuentra vacio se hace referencia al evento InsertarRegistro(cliente) que se encuentra en la clase ClsClienteDAL
if (txtID.Text == "")
{
ClsClienteDAL.InsertarRegistro(cliente);
MessageBox.Show("Registro guardado correctamente", "Aviso del Sistema", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
// Si es que la caja de texto se encuentra distinto a vacio se hace referencia al evento ActualizarRegistro(cliente, Convert.ToInt32(txtID.Text)) que se encuentra en la clase ClsClienteDAL
if (txtID.Text != "")
{
ClsClienteDAL.ActualizarRegistro(cliente, Convert.ToInt32(txtID.Text));
MessageBox.Show("Registro Actualizado correctamente","Aviso del Sitema", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//Invoco al evento LimpiarCtrl(), y vuelvo a cargar la grilla
LimpiarCtrl();
dgv_cliente.DataSource = ClsClienteDAL.ClienteAll();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Evento clic de botón eliminar, capturamos el id e invocamos el evento ElimarRegistro(id).
private void btnEliminar_Click(object sender, EventArgs e)
{
DataGridViewRow row = dgv_cliente.CurrentRow as DataGridViewRow;
//Validación
if (row != null)
{
//Capturamos id de la grilla
int id = Convert.ToInt32(row.Cells["id"].Value);
//Invocamos el evento para la eliminación
ClsClienteDAL.ElimarRegistro(id);
//(Refrescar) Vuelvo a cargar la grilla
dgv_cliente.DataSource = ClsClienteDAL.ClienteAll();
}
}

0 Comentarios