Sei sulla pagina 1di 18

Manual SQL y C SHARP, proyecto final

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final

En este proyecto manejaremos los herramientas: Sql y C shar , con esto manipularemos una base de datos de sql desde c shar y veremos como se maneja un reproductor de Windows Media Player. El programa esta construido por una base de datos echa en Sql que tiene por nombre proyecto 2. En esta imagen podemos observar sus tablas y sus relaciones que tiene de dicha BD.

CUSTOMER
CUSTID

SALGRADE
GRADE LOSAL HISLA

NAME ADDRESS CITY STATE ZIP AREA PHONE REPID CREDITLIMIT COMMENTS

ORD
ORDID

PRODUCT
PRODID DESCRIP

ORDERDATE COMMPLAN CUSTID SHIPDATE TOTAL

EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

PRICE
PRODID STDPRICE MINPRICE STARTDATA ENDDATE

ITEM
ORDID ITEMID PRODID ALCUTALPRICE OTY ITEMTOT

DEPT
DEPTNO DNAME LOC

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final

Bueno no nos enfocaremos en BD ya que nuestro objetivo para esta materia es seguir aprendiendo el lenguaje c Sharp. Bueno el programa esta construido de la siguiente manera. Primero tenemos el form1. Este formulario simplemente creamos una pequea interfaz que sirve como recepcin de datos para que se pueda logear el usuario. Form2. Este formulario muestra un catalogo de las actividades que podemos realizar, en los iconos simplemente tiene cdigo para que muestre los interfaces o los otros formularios. Ver imagen siguiente.

Bueno no se necesita mucha explicacin para entender esta interfaz , se entiende que si pinchas un botn te lleva a la interfaz de dicha etiqueta .

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


En este trabajo el botn y el botn empleado tienen parecido cdigo simplemente cambian en el nombre y sus atributos pero el procedimiento, las funciones, son las mismas asi que explicare solo la interzas em preado que es la que es un poco mas complicada. bueno clic en el botn empleado interfaz. aparacereca la siguiente

bueno aqu tienen la interfaz empleado . si observan la tabla aparece con datos, para ello se tiene que establecer una conexin con una BD de sql. Bueno aqu explico como esta creado este forme Una para poder trabajar con sql tenemos que agregar la librera Data.SqlClient, nos servir para podernos conectar con dicha BD
using System; using System.Collections.Generic;

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


using using using using using using using System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Data.SqlClient;

namespace Proyecto2__ver2 { public partial class Form3 : Form { // . La clase que va a hacer el proceso de impresin DataGridViewPrinter MyDataGridViewPrinter; public Form3() { InitializeComponent(); }

Bueno en esta parte indicamos nuestras variables globales que nos servirn como indicadores; la variable indicador que vemos declarada nos sirve para indicar a los botones que estn habilitados o deshabilitados. Tambin se tiene que declarar las variables necesaria para que se pueda estables la conexin con la BD.
// para evitar rentradas al codigo private bool iniciando = true; public int indicador=0; private DataTable dt; private SqlDataAdapter da; private string conexion = "Initial Catalog=proyecto2;Data Source=LUISPC\\SQLEXPRESS;Integrated Security=SSPI;"; private string seleccion = "SELECT * FROM EMP ";

En cuando carga nuestro Form nosotros agregamos los datos a al dataGrewvie asiendo la conexin con el comando declarado de SQl.
private void Form3_Load(object sender, EventArgs e) { modificar.Enabled = false; eliminar.Enabled = false; da = new SqlDataAdapter(seleccion, conexion); dt = new DataTable(); da.Fill(dt); dataGridView1.DataSource = dt; iniciando = false; }

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


Esta funcin es la que actualiza el dataGrewVie cuando una funcin realiza un cambio a la base de dato. Es como si volviramos a cargar el form3.
private void func_Actializar() { da = new SqlDataAdapter(seleccion, conexion); dt = new DataTable(); da.Fill(dt); dataGridView1.DataSource = dt; }

En esta parte aadimos los datos buscados que se esta buscando en el texbox9 que es el campo donde nosotros ponemos el nombre para buscar el nombre del cliente. Pero esto funcin se activa cuando seleccionamos un cliente del lixbox este tambin se selecciona el cliente en el dataGridview.
private void lista_SelectedIndexChanged(object sender, EventArgs e) { if (iniciando) return; this.listBox1.Text = this.listBox1.SelectedItem.ToString(); this.dataGridView1.ClearSelection(); foreach (DataGridViewRow fila in this.dataGridView1.Rows) { if (fila.Cells["ENAME"].Value == null || fila.Cells == null) { break; } int i = this.textBox9.Text.IndexOf(","); if (i > -1) { string NAME; int EMPNO; NAME = this.textBox9.Text.Substring(0, i).TrimEnd(); EMPNO = Convert.ToInt32 ( this.textBox9.Text.Substring(i, 1).TrimStart()); if (NAME == fila.Cells["ENAME"].Value.ToString() && EMPNO ==Convert.ToInt32 (fila.Cells["EMPNO"].Value.ToString())) { this.dataGridView1.Rows[fila.Index].Selected = true; this.dataGridView1.FirstDisplayedScrollingRowIndex = fila.Index; break; } } else { if (this.textBox9.Text == fila.Cells["ENAME"].Value.ToString())

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


{ //this.dataGridView1.Focus(); this.dataGridView1.Rows[fila.Index].Selected = true; this.dataGridView1.FirstDisplayedScrollingRowIndex = fila.Index; break; } } } modificar.Enabled = true ; eliminar.Enabled = true ; } private void button3_Click(object sender, EventArgs e) { this.Close(); } private void button5_Click(object sender, EventArgs e) { int i = 0; int fila = dataGridView1.Rows.GetRowCount (DataGridViewElementStates .Selected); int fin = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Visible); for ( i=0;i<=fin;i++) { if(dataGridView1.Rows[i].Selected ==true ){fila=i;break;} } fun_eliminar(fila); modificar.Enabled = false; eliminar.Enabled = false; textBox9.Text = ""; }

En esta funcin eliminamos un dato de la tabla, esta funcin recibe un ndice de posicin que es donde se encuentra la fila a eliminar. En la primera condicin decimos que si la tabla esta vaca entonces retornar o salir. Y si la fila es mayor a 1 entonces se procede a eliminar con el comando Delete, posteriormente actualizando y aceptando los cambios como se ven en el cdigo de abajo.
void fun_eliminar(int fila) { //if (fila < 0+fila || fila > dt.Rows.Count - 1) return; if (fila < 0) return; try { // Eliminar la fila de la tabla dt.Rows[fila].Delete(); // Actualizar fsicamente la base de datos

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


da.Update(dt); // Aceptar los cambios en la copia local dt.AcceptChanges(); } catch (DBConcurrencyException ex) { MessageBox.Show("Error de concurrencia:\n" + ex.Message); } catch (Exception ex) { MessageBox.Show(ex.Message); } }

En esta funcin configuramos la impresora de tal manera que al dar clic en la pestaa que tiene el men y elegir la opcin imprimir obtengamos una impresin con los mrgenes establecidos
// funcion que configura la impresora private bool SetupThePrinting() { PrintDialog MyPrintDialog = new PrintDialog(); MyPrintDialog.AllowCurrentPage = false; MyPrintDialog.AllowPrintToFile = false; MyPrintDialog.AllowSelection = false; MyPrintDialog.AllowSomePages = false; MyPrintDialog.PrintToFile = false; MyPrintDialog.ShowHelp = false; MyPrintDialog.ShowNetwork = false; if (MyPrintDialog.ShowDialog() != DialogResult.OK) return false; printDocument1.DocumentName = "Customers Report"; printDocument1.PrinterSettings = MyPrintDialog.PrinterSettings; printDocument1.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings; printDocument1.DefaultPageSettings.Margins =new System.Drawing.Printing.Margins(40, 40, 40, 40); if (MessageBox.Show("Do you want the report to be centered on the page", "InvoiceManager - Center on Page", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) MyDataGridViewPrinter = new DataGridViewPrinter(dataGridView1 ,printDocument1, true, true, "Customers", new Font("Tahoma", 18,

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


FontStyle.Bold, GraphicsUnit.Point), Color.Black, true); else MyDataGridViewPrinter = new DataGridViewPrinter(dataGridView1 ,printDocument1, false, true, "Customers", new Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, true); return true; } private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void imprimirToolStripMenuItem_Click(object sender, EventArgs e) { if (SetupThePrinting()) printDocument1.Print(); } private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { bool more = MyDataGridViewPrinter.DrawDataGridView(e.Graphics); if (more == true) e.HasMorePages = true; } private void vistaPreviaToolStripMenuItem_Click(object sender, EventArgs e) { if (SetupThePrinting()) { PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog(); MyPrintPreviewDialog.Document = printDocument1; MyPrintPreviewDialog.ShowDialog(); } } private void salirToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void guardarToolStripMenuItem_Click(object sender, EventArgs e) { button1.Select(); } private void listBox1_SelectedIndexChanged_1(object sender, EventArgs e) { if (iniciando) return; this.listBox1.Text = this.listBox1.SelectedItem.ToString(); this.dataGridView1.ClearSelection(); foreach (DataGridViewRow fila in this.dataGridView1.Rows) { if (fila.Cells["ENAME"].Value == null || fila.Cells == null)

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


{ break; } int i = this.textBox9.Text.IndexOf(","); if (i > -1) { string NAME; int EMPNO; NAME = this.textBox9.Text.Substring(0, i).TrimEnd(); EMPNO = Convert.ToInt32(this.textBox9.Text.Substring(i, 1).TrimStart()); if (NAME == fila.Cells["ENAME"].Value.ToString() && EMPNO == Convert.ToInt32(fila.Cells["EMPNO"].Value.ToString())) { this.dataGridView1.Rows[fila.Index].Selected = true; this.dataGridView1.FirstDisplayedScrollingRowIndex = fila.Index; break; } } else { if (this.textBox9.Text == fila.Cells["ENAME"].Value.ToString()) { //this.dataGridView1.Focus(); this.dataGridView1.Rows[fila.Index].Selected = true; this.dataGridView1.FirstDisplayedScrollingRowIndex = fila.Index; break; } } } modificar.Enabled = true; eliminar.Enabled = true; }

Esta funcin tiene como objetivo agregar Nuevo cliente a la BD para ello nuevamente volvemos a establecer la conexin, y insertamos los valores como si estuviramos insertando datos con SQL ,cmd es una variable para usar los comandos de SQL, adems de mostrar tambin unos mensajes de verificacin, una cosa que hay que tener en cuenta es que las tablas de SQL estn relacionadas y debemos tener cuidado al meter los datos.
private void button1_Click_2(object sender, EventArgs e) { if (indicador == 0) { SqlConnection Conexion = new SqlConnection("Initial Catalog=proyecto2;Data Source=LUIS-PC\\SQLEXPRESS;Integrated Security=SSPI;"); SqlCommand cmd = new SqlCommand();

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


cmd.CommandType = System.Data.CommandType.Text; cmd.CommandText = "insert into emp values(" + textBox1.Text + ", '" + textBox2.Text + "', '" + textBox3.Text + "', " + textBox4.Text + ", " + textBox5.Text + ", " + textBox1.Text + ", " + textBox7.Text + ", " + textBox8.Text + ")"; cmd.Connection = Conexion; try { Conexion.Open(); cmd.ExecuteNonQuery(); MessageBox.Show("Los datos se Guardaron correctamente", "verificacion"); func_Actializar(); poneainicio(); } catch (SqlException ex) { MessageBox.Show(ex.ToString()); } finally { Conexion.Close(); }

} if (indicador == 1) { SqlConnection Conexion = new SqlConnection("Initial Catalog=proyecto2;Data Source=LUIS-PC\\SQLEXPRESS;Integrated Security=SSPI;"); SqlCommand cmd = new SqlCommand(); cmd.CommandType = System.Data.CommandType.Text; string actualizar = (" update emp set empno='"+textBox1.Text+"', ename ='"+ textBox2.Text + "', job ='" + textBox3.Text + "', mgr ='" + textBox4.Text + "', hiredate = '" + textBox5.Text + "', sal= '" + textBox1.Text + "', comm='" + textBox7.Text + "', deptno='" + textBox8.Text +"'where empno="+textBox1.Text ); cmd.CommandText = actualizar; cmd.Connection = Conexion; try { Conexion.Open(); cmd.ExecuteNonQuery(); func_Actializar(); poneainicio(); MessageBox.Show("Los datos se actualizaron satisfactoriamente", "verificacion"); indicador = 0; } catch (SqlException ex) { MessageBox.Show(ex.ToString()); } finally { Conexion.Close(); }

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final

} }

Esta funcin busca el nombre del empleado que introduces en el texbox9 y los resultados los va agregando a la lista, se hace una consulta que nos mostrara con el operador LIKE que nos muestre todos los nombre que empiecen con la letra o el nombre introducido en el tex box.
private void buscar(object sender, EventArgs e) { if (iniciando) return; DataRow[] filas; filas = dt.Select("ENAME LIKE '%" + textBox9.Text + "%'"); this.listBox1.Items.Clear(); if (filas.Length > 0) { foreach (DataRow dr in filas) { this.listBox1.Items.Add(dr["EMPNO"].ToString() + "," + dr["ENAME"].ToString());// + "," + dr["JOB"].ToString() + "," + dr["MGR"].ToString() + "," + dr["HIREDATE"].ToString() + "," + dr["SAL"].ToString() + "," + dr["COMM"].ToString() + "," + dr["DEPTNO"].ToString()); } }

En esta funcin modificamos o actualizamos los datos de dicho empleado cuando el usuario de clic en el botn modificar.
private void button4_modificar(object sender, EventArgs e) // boton modificar {

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


groupBox1Nuevo.Text = "Modificar empleado"; int i = 0; int fila = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected); int fin = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Visible); for (i = 0; i <= fin; i++) { if (dataGridView1.Rows[i].Selected == true) { fila = i; break; } } textBox1.Text = dataGridView1.Rows[fila].Cells[0].Value.ToString (); textBox2.Text = dataGridView1.Rows[fila].Cells[1].Value.ToString(); textBox3.Text = dataGridView1.Rows[fila].Cells[2].Value.ToString(); textBox4.Text = dataGridView1.Rows[fila].Cells[3].Value.ToString(); textBox5.Text = dataGridView1.Rows[fila].Cells[4].Value.ToString(); textBox6.Text = dataGridView1.Rows[fila].Cells[5].Value.ToString(); textBox7.Text = dataGridView1.Rows[fila].Cells[6].Value.ToString(); textBox8.Text = dataGridView1.Rows[fila].Cells[7].Value.ToString(); modificar.Enabled=false ; eliminar.Enabled = false; textBox9.Text = ""; indicador = 1; } private void button6_nuevo(object sender, EventArgs e)//boton nuevo { groupBox1Nuevo.Text = "Nuevo Empleado "; } private void button2_Click(object sender, EventArgs e) { poneainicio(); }

Esta funcin se encarga de poner los textBoxs en blanco y devolviendo el control a los objetos correspondientes.
void poneainicio() { textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; textBox6.Text = ""; textBox7.Text = ""; textBox8.Text = ""; groupBox1Nuevo.Show(); modificar.Enabled = false; eliminar.Enabled = false; }

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


Esta funcin es la encargada de eliminar el registro seleccionado por el usurario ; se declaran dos variables una que indica el ndice de inicio de la tabla y la otra que indica el final en nuestro caso son las variables fila, fin; despus se recorre el arreglo buscando la fila seleccionada una vez que la encuentra se sale del ciclo for. A continuacin se crea una cadena , esta cadena se le agregan los datos para presentrselos al usuario por que son los datos que va a eliminar.
private void eliminar_Click(object sender, EventArgs e) { int fila = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected); int fin = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Visible); for (int i = 0; i <= fin; i++) { if (dataGridView1.Rows[i].Selected == true) { fila = i; break; } } string cadena = null; cadena = dataGridView1.Rows[fila].Cells[0].Value.ToString() + " " + dataGridView1.Rows[fila].Cells[1].Value.ToString();

En seta parte del programa se registro asido eliminado


if

le confirma al usuario que el

(MessageBox.Show("Seguro que dese eliminar el registro del empleado?\n"+cadena, "Confirmacion", MessageBoxButtons.YesNo) == DialogResult.Yes) { fun_eliminar(fila); MessageBox.Show("El registro asido eliminado"); } poneainicio(); } private void fun(object sender, DataGridViewCellEventArgs e) { modificar.Enabled = true; eliminar.Enabled = true; }

} }

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final

Ahora veamos el formulario que contiene multimedia, a esta interfaz llegamos dando clic en el botn multimedia del formulario catalogo visto anteriormente, a continuacin se muestra la interfaz del formulario

Si observamos la interfaz la lista de reproduccin esta contenida en un lixbox y los botones adelante atrs , el botn que carga el video .Bueno para hacer la reproduccin de los videos y las canciones simplemente jalamos el reproductor de windows media player, a veces no esta definido en la barra de herramientas de c sharp, hay que agregar el complemento dando clic en el men tools en seguida damos clic en elegir tools o herramientas, nos aparecer una nueva venta , en esa ventana elegimos la pestaa 2 que dice COM components , ah buscamos el componente de Windows media, seleccionamos y damos agregar.

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


namespace Proyecto2__ver2 { public partial class Form5 : Form { public Form5() { InitializeComponent(); }

Adems cabe mencionar que todas las clases estn echas en el mismo namespace , en esta parte del cdigo se crean las variables globales, tenemos un arreglo de string que almacenara las rutas que abriremos para despus poderlas reproducir sin abrirlas otra vez, tambin tenemos un contador que indica la posicin de la ruta.
string ruta; int cont=0; string[] arrrutas;

Esta funcin abre el archive si observamos la ruta del archive la almacenamos en la variable ruta. Despus cambiamos se la asignamos a la URL del reproductor, bueno esta funcin abre y reproduce el archivo.
void AbrirArchivo() { OpenFileDialog abrirarchivo = new OpenFileDialog(); abrirarchivo.Filter = "Archivo|*"; abrirarchivo.ShowDialog(); ruta = abrirarchivo.FileName; axWindowsMediaPlayer1.URL = ruta; Form5.ActiveForm.Text = ruta; }

Este botn tiene como etiqueta cargar, as que eso hace carga el archive en esta parte tambin asignamos la ruta leda a nuestro arreglo y obtenemos el nombre del archive con la funcin Path.GetFileNameWithoutExtension(ruta); que devuelve el nombre del archivo , el nombre del archivo lo almacenamos en el listBox1 y el cont lo aumentamos;
private void button1_Click(object sender, EventArgs e) { AbrirArchivo(); string nombarch; nombarch=Path.GetFileNameWithoutExtension(ruta); listBox1.Items.Add(nombarch);

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


arrrutas [cont]=ruta; cont++; } private void button3_Click(object sender, EventArgs e) { this.Close(); }

Este evento tiene funcin cuando seleccionamos un elemento de la lista de reproduccin, aqu la URL la cambiamos , primero obtenemos la posicin del elemento seleccionado que ser el indicador de para el arrutas , depuse extraemos la ruta del arreglo.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { axWindowsMediaPlayer1.URL = arrrutas[ listBox1.Items.IndexOf(listBox1.SelectedItem.ToString())]; } private void Form5_Load(object sender, EventArgs e) { arrrutas = new string[40]; }

Este botn es el encargado de reproducir la cancin anterior, primero obtenemos la posicin del tem seleccionado y este ndice le disminuimos 1 , des puses seleccionamos el tem menos uno que ser la cancin anterior, este mismo procedimiento lo realizamos para el botn 4 pero con la diferencia que a el le aumentamos 1.
private void button2_Click(object sender, EventArgs e) { int c=listBox1.Items.IndexOf(listBox1.SelectedItem.ToString()); if (c == 0) { } else { axWindowsMediaPlayer1.URL = arrrutas[(listBox1.Items.IndexOf(listBox1.SelectedItem.ToString()) - 1)]; listBox1.SelectedIndex = c; listBox1.SetSelected(c - 1, true); } } private void button4_Click(object sender, EventArgs e) { int c = listBox1.Items.IndexOf(listBox1.SelectedItem.ToString());

Echo por Luis ngel Sanjun Acatitla

Manual SQL y C SHARP, proyecto final


if (c > (listBox1.Items.Count)-1) { } else { axWindowsMediaPlayer1.URL = arrrutas[(listBox1.Items.IndexOf(listBox1.SelectedItem.ToString()) + 1)]; listBox1.SelectedIndex = c; listBox1.SetSelected(c+1, true); } } private void button5_Click(object sender, EventArgs e) { for (int i = 0; i <= 40; i++) { arrrutas[i] =""; cont = 0; } listBox1.Items.Clear(); } } }

Echo por Luis ngel Sanjun Acatitla

Potrebbero piacerti anche