Sei sulla pagina 1di 14

Control DataGridView

Javier Serrano

Programación .NET II

Instituto IACC

28-07-2019
Desarrollo

Ejecución.

Acceso Conectado.
Selección de empleado.

Busqueda con filtros.


Acceso Desconectado.

Selección de orden para visualizar su detalle.

Combobox con filtros de búsqueda.


Codigo Fuente.

Conexión y consultas:

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ControlGridview
{
public class ConexionDatos
{
public string _stringConexion =
"DataSource=localhost;Database=northwind;Uid=root;Pwd=root;Convert Zero Datetime=True";
public MySqlConnection conexion { get; set; }
public DataTable _dtOrdenes;

public ConexionDatos()
{
conexion = new MySqlConnection(_stringConexion);
}

public DataTable GetAllEmpleados()


{
string query = "SELECT EmployeeID as ID, concat(FirstName,' ',LastName) as
Nombre FROM northwind.employees order by EmployeeID;";
MySqlCommand cmd = new MySqlCommand(query, conexion);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query, conexion);
DataTable dt = new DataTable("employees");
returnVal.Fill(dt);
this.conexion.Close();
return dt;
}

public DataTable GetOrdenesByIdEmpleado(int IdEmpleado)


{
string query = $"SELECT c.CompanyName,o.* FROM orders o inner join customers
c on o.CustomerID = c.CustomerID where o.EmployeeId = {IdEmpleado}; ";
//string query = $"select * from orders where EmployeeId = {IdEmpleado}";
MySqlCommand cmd = new MySqlCommand(query, conexion);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query, conexion);
DataTable dt = new DataTable("orders");
returnVal.Fill(dt);
this.conexion.Close();
_dtOrdenes = dt;
return dt;
}

public DataTable GetAllOrdenes()


{
string query = "SELECT c.CompanyName,o.* FROM orders o inner join customers c
on o.CustomerID = c.CustomerID; ";
//string query = $"select * from orders where EmployeeId = {IdEmpleado}";
MySqlCommand cmd = new MySqlCommand(query, conexion);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query, conexion);
DataTable dt = new DataTable("orders");
returnVal.Fill(dt);
this.conexion.Close();
_dtOrdenes = dt;
return dt;
}

public DataTable GetOrdeneDetalleByIdorden(int idOrden)


{
string query = $"SELECT p.ProductName,od.* FROM orderdetails od inner join
products p on od.ProductID = p.ProductID where OrderId = {idOrden}";
//string query = $"select * from orders where EmployeeId = {IdEmpleado}";
MySqlCommand cmd = new MySqlCommand(query, conexion);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query, conexion);
DataTable dt = new DataTable("ordersdetails");
returnVal.Fill(dt);
this.conexion.Close();
_dtOrdenes = dt;
return dt;
}

public DataTable GetPaises()


{
string query = "SELECT distinct ShipCountry as Pais FROM orders order by
ShipCountry;";
//string query = $"select * from orders where EmployeeId = {IdEmpleado}";
MySqlCommand cmd = new MySqlCommand(query, conexion);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query, conexion);
DataTable dt = new DataTable("Paises");
returnVal.Fill(dt);
this.conexion.Close();
_dtOrdenes = dt;
return dt;
}

public DataTable GetNombres()


{
string query = "SELECT distinct ShipName as Nombres FROM northwind.orders
order by ShipName;";
//string query = $"select * from orders where EmployeeId = {IdEmpleado}";
MySqlCommand cmd = new MySqlCommand(query, conexion);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query, conexion);
DataTable dt = new DataTable("Nombres");
returnVal.Fill(dt);
this.conexion.Close();
_dtOrdenes = dt;
return dt;
}
}
}

Conectado:

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;

namespace ControlGridview
{
public partial class Conectado : Form
{

public ConexionDatos _cnn = new ConexionDatos();


public Conectado()
{
InitializeComponent();
SetControlesNoVisibles();
CargarEmpleados();
}

private void CargarEmpleados()


{
try
{
var dtEmpleados = _cnn.GetAllEmpleados();
dgvEmpleados.DataSource = dtEmpleados;

foreach (DataGridViewRow row in dgvEmpleados.Rows)


{
row.Selected = false;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}

private void RadioButton_CheckedChanged(object sender, EventArgs e)


{
RadioButton rb = sender as RadioButton;

SetControlesNoVisibles();

if (rb != null)
{
switch (rb.Name)
{
case "rbFechaEnvio":
this.dtpFechaEnvio.Visible = true;
break;
case "rbCarga":
this.txtCargaDesde.Visible = true;
this.txtCargaHasta.Visible = true;
this.lbdCarga.Visible = true;
this.lbhCarga.Visible = true;
break;
case "rbOrdenFecha":
this.dtpOrdenDesde.Visible = true;
this.dtpOrdenHasta.Visible = true;
this.lbdOrden.Visible = true;
this.lbhOrden.Visible = true;
break;
}

}
}

private void SetControlesNoVisibles()


{
this.lbdCarga.Visible = false;
this.lbdOrden.Visible = false;
this.lbhCarga.Visible = false;
this.lbhOrden.Visible = false;
this.dtpFechaEnvio.Visible = false;
this.dtpOrdenDesde.Visible = false;
this.dtpOrdenHasta.Visible = false;
this.txtCargaDesde.Visible = false;
this.txtCargaHasta.Visible = false;
}

private void DgvEmpleados_CellClick(object sender, DataGridViewCellEventArgs e)


{
int id = (int)dgvEmpleados.Rows[e.RowIndex].Cells[0].Value;

try
{
dgvOrdenes.DataSource = null;
var dtOrders = _cnn.GetOrdenesByIdEmpleado(id);
dgvOrdenes.DataSource = dtOrders;
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}

private void BtnBuscar_Click(object sender, EventArgs e)


{
int indiceColumna = 0;
int posicion = -1;
DataRow[] filas;
string expresion = string.Empty;
DataTable temp = (DataTable)dgvOrdenes.DataSource;
if (rbCarga.Checked)
{
decimal CargaDesde = decimal.Parse(this.txtCargaDesde.Text);
decimal CargaHasta = decimal.Parse(this.txtCargaHasta.Text);
indiceColumna = 7;
expresion = $"Freight >= {CargaDesde} and Freight <= {CargaHasta}";

}
else if (rbFechaEnvio.Checked)
{
var fecha = dtpFechaEnvio.Value.ToString("yyyy/MM/dd");
expresion = $"shippedDate = '{fecha}'";
}
else
{
var fechaOrdeDesde = dtpOrdenDesde.Value.ToString("yyyy/MM/dd");
var fechaOrdeHasta = dtpOrdenHasta.Value.ToString("yyyy/MM/dd");
expresion = $" orderDate >= '{fechaOrdeDesde}' and orderDate <=
'{fechaOrdeHasta}'";
}

foreach (DataGridViewRow r in dgvOrdenes.Rows)


{
r.Selected = false;
}

filas = temp.Select(expresion);
if (filas.Length > 0)
{
lblCoincidencias.Text = $"{filas.Length} Coincidencia";

if (rbFechaEnvio.Checked)
{
posicion = temp.Rows.IndexOf(filas[0]);
dgvOrdenes.CurrentCell = dgvOrdenes.Rows[posicion].Cells[0];
}
else
{
for (int i = 0; i < filas.Length - 1; i++)
{
posicion = temp.Rows.IndexOf(filas[i]);
dgvOrdenes[indiceColumna, posicion].Selected = true;
}
}
}
else
{
MessageBox.Show("No existe coincidencias para el criterio ingresado");
}
}
}
}
Desconectado:

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;

namespace ControlGridview
{
public partial class Desconectado : Form
{
public ConexionDatos _cnn = new ConexionDatos();
DataTable dtDetalleOrden;
public Desconectado()
{
InitializeComponent();
CargarOrdenes();
CargarCombosBusqueda();
}

private void CargarOrdenes()


{
try
{
var dtOrdenes = _cnn.GetAllOrdenes();
dgvOrdenes.DataSource = dtOrdenes;

foreach (DataGridViewRow row in dgvOrdenes.Rows)


{
row.Selected = false;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}

private void DgvOrdenes_CellClick(object sender, DataGridViewCellEventArgs e)


{
int id = (int)dgvOrdenes.Rows[e.RowIndex].Cells[1].Value;

try
{
dgvDetalleOrden.DataSource = null;
var dtOrdersdetail = _cnn.GetOrdeneDetalleByIdorden(id);

dgvDetalleOrden.DataSource = dtOrdersdetail;

}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}

private void CargarCombosBusqueda()


{
try
{

var dtPaises = _cnn.GetPaises();


var dtNombres = _cnn.GetNombres();

this.cbPaises.DataSource = dtPaises;
this.cbPaises.DisplayMember = "Pais";
this.cbPaises.ValueMember = "Pais";

this.cbNombres.DataSource = dtNombres;
this.cbNombres.DisplayMember = "Nombres";
this.cbNombres.ValueMember = "Nombres";

}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}

private void CbPaises_SelectionChangeCommitted(object sender, EventArgs e)


{
string pais = string.Empty;
string filtro = string.Empty;
DataView temp;
pais = cbPaises.SelectedValue.ToString();
filtro = $"ShipCountry = '{pais}'";
temp = new DataView((DataTable)dgvOrdenes.DataSource, filtro, "ShipCountry
Desc", DataViewRowState.CurrentRows);
dgvOrdenes.DataSource = temp;
}

private void CbNombres_SelectionChangeCommitted(object sender, EventArgs e)


{
string nombres = string.Empty;
string filtro = string.Empty;
DataView temp;
nombres = cbNombres.SelectedValue.ToString();
filtro = $"ShipName = '{nombres}'";
temp = new DataView((DataTable)dgvOrdenes.DataSource, filtro, "ShipName
Desc", DataViewRowState.CurrentRows);
dgvOrdenes.DataSource = temp;
}

private void BtnOrdenVia_Click(object sender, EventArgs e)


{
ListSortDirection orden = new ListSortDirection();
DataGridViewColumn columna = new DataGridViewColumn();
columna = dgvOrdenes.Columns["ShipVia"];

if (rbViaAsc.Checked)
orden = ListSortDirection.Ascending;

if (rbViaDesc.Checked)
orden = ListSortDirection.Descending;

dgvOrdenes.Sort(columna, orden);

private void BtnOrdenCiudad_Click(object sender, EventArgs e)


{
ListSortDirection orden = new ListSortDirection();
DataGridViewColumn columna = new DataGridViewColumn();

columna = dgvOrdenes.Columns["ShipCity"];

if (rbCiuAsc.Checked)
orden = ListSortDirection.Ascending;

if (rbCiuDesc.Checked)
orden = ListSortDirection.Descending;

dgvOrdenes.Sort(columna, orden);
}
}
}

Principal:

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;

namespace ControlGridview
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

private void AccesoConectadoToolStripMenuItem_Click(object sender, EventArgs e)


{
Conectado cnt = new Conectado();
cnt.MdiParent = this;
cnt.Show();
}

private void AccesoDesconectadoToolStripMenuItem_Click(object sender, EventArgs


e)
{
Desconectado dsc = new Desconectado();
dsc.MdiParent = this;
dsc.Show();
}
}
}
Bibliografía

 Contenidos Semana 7.

Potrebbero piacerti anche