lunes, 7 de noviembre de 2016

Práctica 17. C# con MySql. Creando un sistema de registro de libros.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Practica_17
{
    public class Cliente
    {
        public int Id { get; set; }
        public string Nombre { get; set; }
        public string Apellido { get; set; }
        public string Fecha_Nacimiento { get; set; }
        public string Direccion { get; set; }

        public Cliente() { }

        public Cliente(int pId, string pNombre, string pApellido, string pFecha_Nac, string pDireccion)
        {
            this.Id = pId;
            this.Nombre = pNombre;
            this.Apellido = pApellido;
            this.Fecha_Nacimiento = pFecha_Nac;
            this.Direccion = pDireccion;
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Practica_17
{
    public partial class BuscarCliente : Form
    {
        public BuscarCliente()
        {
            InitializeComponent();
        }
        public Cliente ClienteSeleccionado { get; set; }
        private void btnBuscar_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = ClientesDAL.Buscar(txtNombre.Text, txtApellido.Text);
        }

        private void btnAceptar_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 1)
            {
                int id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);
                ClienteSeleccionado = ClientesDAL.ObtenerCliente(id);

                this.Close();
            }
            else
                MessageBox.Show("debe de seleccionar una fila");
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            txtNombre.Clear();
            txtApellido.Clear();
        }

        private void BuscarCliente_Load(object sender, EventArgs e)
        {

        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Practica_17
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public Cliente clienteactual { get; set; }

        private void txtNombre_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtApellido_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtDireccion_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnGuardar_Click(object sender, EventArgs e)
        {
          
            if (string.IsNullOrWhiteSpace(txtNombre.Text) || string.IsNullOrWhiteSpace(txtApellido.Text) ||
                           string.IsNullOrWhiteSpace(txtDireccion.Text))
          
                MessageBox.Show("Hay Uno o mas Campos Vacios!", "Campos Vacios!!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  
           
            else
            {
                 Cliente pCliente = new Cliente();
                pCliente.Nombre = txtNombre.Text.Trim();
                pCliente.Apellido = txtApellido.Text.Trim();
                pCliente.Fecha_Nacimiento = dtpFechaNacimiento.Value.Year + "/" + dtpFechaNacimiento.Value.Month + "/" + dtpFechaNacimiento.Value.Day;
                pCliente.Direccion = txtDireccion.Text.Trim();

                int resultado = ClientesDAL.Agregar(pCliente);
                if (resultado > 0)
                {
                    MessageBox.Show("Cliente Guardado Con Exito!!", "Guardado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Limpiar();
                    Deshabilitar();
                }
                else
                {
                    MessageBox.Show("No se pudo guardar el cliente", "Fallo!!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }
       
        private void toolStripButton5_Click(object sender, EventArgs e)
        {

            BuscarCliente buscar = new BuscarCliente();
            buscar.ShowDialog();
            if (buscar.ClienteSeleccionado != null)
            {
                btnActializar.Enabled = true;
                btnElim.Enabled = true;
                Habilitar();
                btnGuardar.Enabled = false;
                clienteactual = buscar.ClienteSeleccionado;
                txtNombre.Text = buscar.ClienteSeleccionado.Nombre;
                txtApellido.Text = buscar.ClienteSeleccionado.Apellido;
                txtDireccion.Text= buscar.ClienteSeleccionado.Direccion;
                dtpFechaNacimiento.Text = buscar.ClienteSeleccionado.Fecha_Nacimiento;
               
            }

        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtNombre.Text) || string.IsNullOrWhiteSpace(txtApellido.Text) ||
                           string.IsNullOrWhiteSpace(txtDireccion.Text))
          
                MessageBox.Show("Hay Uno o mas Campos Vacios!", "Campos Vacios!!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
              
           
            else
            {

                Cliente pCliente = new Cliente();
                pCliente.Nombre = txtNombre.Text.Trim();
                pCliente.Apellido = txtApellido.Text.Trim();
                pCliente.Fecha_Nacimiento = dtpFechaNacimiento.Value.Year + "/" + dtpFechaNacimiento.Value.Month + "/" + dtpFechaNacimiento.Value.Day;
                pCliente.Direccion = txtDireccion.Text.Trim();
                pCliente.Id = clienteactual.Id;

                if (ClientesDAL.Actualizar(pCliente) > 0)
                {
                    MessageBox.Show("Los datos del cliente se actualizaron", "Datos Actualizados", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Limpiar();
                }
                else
                {
                    MessageBox.Show("No se pudo actualizar", "Error al Actualizar", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                }
            }
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Esta Seguro que desea eliminar el Cliente Actual", "Estas Seguro??", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (ClientesDAL.Eliminar(clienteactual.Id) > 0)
                {
                    MessageBox.Show("Cliente Eliminado Correctamente!", "Cliente Eliminado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Limpiar();
                    Deshabilitar();
                }
                else
                {
                    MessageBox.Show("No se pudo eliminar el Cliente", "Cliente No Eliminado", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            else
                MessageBox.Show("Se cancelo la eliminacion", "Eliminacion Cancelada", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            Limpiar();
            Habilitar();
        }
        void Limpiar()
        {
            txtNombre.Clear();
            txtApellido.Clear();
            txtDireccion.Clear();
            dtpFechaNacimiento.ResetText();

        }
        void Habilitar()
        {
            txtNombre.Enabled = true;
            txtApellido.Enabled = true;
            txtDireccion.Enabled = true;
            dtpFechaNacimiento.Enabled = true;
            btnGuardar.Enabled = true;
            btnCancelar.Enabled = true;

        }
        void Deshabilitar()
        {
            txtNombre.Enabled = false;
            txtApellido.Enabled = false;
            txtDireccion.Enabled = false;
            dtpFechaNacimiento.Enabled = false;
            btnGuardar.Enabled = false;
            btnElim.Enabled = false;
            btnActializar.Enabled = false;
            btnCancelar.Enabled = false;

            btnNuevo.Enabled = true;

        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            Limpiar();
            Deshabilitar();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

     
       

     
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace Practica_17
{
    class ClientesDAL
    {
        public static int Agregar(Cliente pCliente)
        {

            int retorno = 0;

            MySqlCommand comando = new MySqlCommand(string.Format("Insert into clientes (Nombre, Apellido, Fecha_Nacimiento, Direccion) values ('{0}','{1}','{2}', '{3}')",
                pCliente.Nombre, pCliente.Apellido, pCliente.Fecha_Nacimiento, pCliente.Direccion), BdComun.ObtenerConexion());
            retorno = comando.ExecuteNonQuery();
            return retorno;
        }
        public static List<Cliente> Buscar(string pNombre, string pApellido)
        {
            List<Cliente> _lista = new List<Cliente>();

            MySqlCommand _comando = new MySqlCommand(String.Format(
           "SELECT IdCliente, Nombre, Apellido, Fecha_Nacimiento, Direccion FROM clientes  where Nombre ='{0}' or Apellido='{1}'", pNombre, pApellido), BdComun.ObtenerConexion());
            MySqlDataReader _reader = _comando.ExecuteReader();
            while (_reader.Read())
            {
                Cliente pCliente = new Cliente();
                pCliente.Id = _reader.GetInt32(0);
                pCliente.Nombre = _reader.GetString(1);
                pCliente.Apellido = _reader.GetString(2);
                pCliente.Fecha_Nacimiento = _reader.GetString(3);
                pCliente.Direccion = _reader.GetString(4);


                _lista.Add(pCliente);
            }

            return _lista;
        }
        public static Cliente ObtenerCliente(int pId)
        {
            Cliente pCliente = new Cliente();
            MySqlConnection conexion = BdComun.ObtenerConexion();

            MySqlCommand _comando = new MySqlCommand(String.Format("SELECT IdCliente, Nombre, Apellido, Fecha_Nacimiento, Direccion FROM clientes where IdCliente={0}", pId), conexion);
            MySqlDataReader _reader = _comando.ExecuteReader();
            while (_reader.Read())
            {
                pCliente.Id = _reader.GetInt32(0);
                pCliente.Nombre = _reader.GetString(1);
                pCliente.Apellido = _reader.GetString(2);
                pCliente.Fecha_Nacimiento = _reader.GetString(3);
                pCliente.Direccion = _reader.GetString(4);

            }

            conexion.Close();
            return pCliente;

        }

        public static int Actualizar(Cliente pCliente)
        {
            int retorno = 0;
            MySqlConnection conexion = BdComun.ObtenerConexion();

            MySqlCommand comando = new MySqlCommand(string.Format("Update clientes set Nombre='{0}', Apellido='{1}', Fecha_Nacimiento='{2}', Direccion='{3}' where IdCliente={4}",
                pCliente.Nombre, pCliente.Apellido, pCliente.Fecha_Nacimiento, pCliente.Direccion, pCliente.Id), conexion);

            retorno = comando.ExecuteNonQuery();
            conexion.Close();

            return retorno;


        }

        public static int Eliminar(int pId)
        {
            int retorno = 0;
            MySqlConnection conexion = BdComun.ObtenerConexion();

            MySqlCommand comando = new MySqlCommand(string.Format("Delete From clientes where IdCliente={0}", pId), conexion);

            retorno = comando.ExecuteNonQuery();
            conexion.Close();

            return retorno;

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace Practica_17
{
    public class BdComun
    {
        public static MySqlConnection ObtenerConexion()
        {
            MySqlConnection conectar = new MySqlConnection("server=127.0.0.1; database=Tutorial; Uid=root; pwd=root;");

            conectar.Open();
            return conectar;
        }
    }
}