Professional Documents
Culture Documents
Private Sub Cancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cancelar.Click Dim salir As Integer Dim cancelar As Integer salir = MsgBox("quiere cancelar?", 291, "salir") If (salir = 6) Then Me.Close() Else If salir = 7 Then salir = MsgBox("continuar en la aplicacion") Else cancelar = 2 cancelar = MsgBox("siga en el programa") End If End If End Sub VALIDACIONES Private Sub txtcedula_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtcedula.KeyPress If Asc(e.KeyChar) = 13 Or Asc(e.KeyChar) = 8 Then Exit Sub If Not IsNumeric(e.KeyChar) Then MsgBox("por favor ingrese solo numeros", MsgBoxStyle.OkOnly, MessageBoxIcon.Information) e.Handled = True End If End Sub Private Sub txtsalario_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtsalario.KeyPress If Asc(e.KeyChar) = 13 Or Asc(e.KeyChar) = 8 Then Exit Sub If Not IsNumeric(e.KeyChar) Then MsgBox("por favor ingrese solo numeros", MsgBoxStyle.OkOnly, MessageBoxIcon.Information) e.Handled = True End If End Sub Private Sub txtnombre_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtnombre.KeyPress If InStr(1, "abcdefghijkmnlopqrstuvwxyz. " & Chr(8), e.KeyChar) = 0 Then e.KeyChar = "" End If End Sub Private Sub txtapellidos_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtapellidos.KeyPress If InStr(1, "abcdefghijkmnlopqrstuvwxyz. " & Chr(8), e.KeyChar) = 0 Then e.KeyChar = "" End If
Private Sub txtcodigoserv_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Select Case e.KeyChar Case "A" To "Z", "a" To "z", "0" To "9", Chr(32), Chr(8) '8(borrar), 32(espacio) Case Chr(13) 'chr:para q al oprimir enter pase al otro objeto If txtcodigoserv.Text = "" Then txtcodigoserv.Focus() Else txtnombre_servicio.Focus() End If Case Else MessageBox.Show("Caracter no permitido", "Error...") e.Handled = True 'para que solo acepte las teclas validadas End Select End Sub
Private Sub t1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles t1.KeyPress If InStr(1, "0123456789." & Chr(8), e.KeyChar) = 0 Then e.KeyChar = "" End If End Sub
CONTROLES
Private Sub activar_controles() primr.Enabled = True antr.Enabled = True sigr.Enabled = True ultr.Enabled = True guar.Enabled = True elimr.Enabled = True actr.Enabled = True End Sub PARA CONFIGURAR LA RUTA DE LA BASE DE DATOS
Public Class empleados Dim conexion As MySqlConnection Dim ruta As String = My.Settings.trabajoConnectionString Dim tabla As DataTable Dim insertar As New MySqlDataAdapter Dim consultar As New MySqlDataAdapter Dim memoria As New MySqlCommandBuilder Dim data As DataSet Dim enlace As Binding Dim mycomando As MySqlCommand Dim myadapter As MySqlDataReader Dim mydata As New DataTable Dim mydataset As DataSet Dim fila As DataRow Dim posicion As Integer
LUEGO Private Sub btningresar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btningresar.Click Try conexion = New MySqlConnection conexion.ConnectionString = ruta conexion.Open() tabla = New DataTable consultar = New MySqlDataAdapter("Insert Into empleados Values('" & txtcedula.Text & "','" & txtnombre.Text & "','" & txtapellidos.Text & "','" & txtexperiencia.Text & "','" & txtestudio.Text & "','" & txtcargo.Text & "')", conexion) memoria = New MySqlCommandBuilder(consultar) MessageBox.Show("Registro Ingresado") consultar.Fill(tabla) DataGridView1.DataSource = tabla Catch ex As Exception MsgBox("Error en:" & ex.Message, MsgBoxStyle.Critical) Finally conexion.Close() End Try txtcedula.Text = "" txtnombre.Text = "" txtapellidos.Text = "" txtexperiencia.Text = "" txtestudio.Text = "" txtcargo.Text = "" txtcedula.Focus() End Sub
FUNCION LLENAR CAJAS DE TEXTO CON LO DEL DATAGRID Private Sub llenartext() t1.Text = dgcli.Item(0, dgcli.CurrentRow.Index).Value t2.Text = dgcli.Item(1, dgcli.CurrentRow.Index).Value t3.Text = dgcli.Item(2, dgcli.CurrentRow.Index).Value t4.Text = dgcli.Item(3, dgcli.CurrentRow.Index).Value t5.Text = dgcli.Item(4, dgcli.CurrentRow.Index).Value End Sub
Private Sub TXTUSUARIO_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtusuario.TextChanged End Sub Private Sub TXTCONTRASEA_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtcontrasea.TextChanged txtcontrasea.CharacterCasing = CharacterCasing.Upper End Sub
'.................TECLAS RAPIDAS................
Protected Overrides Sub OnKeyUp(ByVal e As KeyEventArgs) Select Case e.KeyData Case Keys.Escape SALIR() Case Keys.Control + Keys.G GUARDAREMP() Case Keys.Control + Keys.E ELIMINAREMP() Case Keys.Control + Keys.V VEREMPLEADOS() Case Keys.F12 MOSTRARAYUDA() Case Keys.Return, CType(65584, Keys) End Select End Sub
End Sub
CLAVE
Imports MySql.Data Imports MySql.Data.MySqlClient Public Class INGRESO Private veces As Integer = 0 Private Const NumeroIntentos As Integer = 3 Private cadenaCnn As String = "SERVER=localhost;USER=root;password=111;DATABASE=MILENIUM" Private Function comprobarUsuario( _ ByVal nombre As String, _ ByVal clave As String) As Boolean ' Conectar a la base de datos Dim cnn As MySqlConnection = Nothing ' Try ' Conectar a la base de datos de MySQL ' (la cadena debe estar inicializada previamente) cnn = New MySqlConnection(cadenaCnn) cnn.Open() ' Definir la cadena que vamos a usar para comprobar ' si el usuario y el password son correctos. ' Utilizo parmetros para evitar inyeccin de cdigo. Dim sel As New System.Text.StringBuilder ' Usando COUNT(*) nos devuelve el total que coincide ' con lo indicado en el WHERE, ' por tanto, si la clave y el usuario son correctos, ' devolver 1, sino, devolver 0 sel.Append("SELECT COUNT(*) FROM USUARIOS ") sel.Append("WHERE USUARIO = ?Administrador AND PASSWORD = ?password") ' Definir el comando que vamos a ejecutar Dim cmd As New MySqlCommand(sel.ToString, cnn) ' Creamos los parmetros cmd.Parameters.Add("?Administrador", MySqlDbType.VarChar, 20) cmd.Parameters.Add("?password", MySqlDbType.VarChar, 15) ' ' Asignamos los valores recibidos como parmetro cmd.Parameters("?Administrador").Value = nombre cmd.Parameters("?password").Value = clave ' ' Ejecutamos la consulta ' ExecuteScalar devuelve la primera columna de la primera fila ' por tanto, devolver el nmero de coincidencias halladas, ' que si es 1, quiere decir que el usuario y el password son correctos. Dim t As Integer = CInt(cmd.ExecuteScalar()) ' Cerramos la conexin cnn.Close() ' ' Si el valor devuelto es cero ' es que no es correcto.
If t = 0 Then Return False End If Catch ex As Exception MessageBox.Show("ERROR al conectar a la base de datos: " & vbCrLf & _ ex.Message, "Comprobar usuario", MessageBoxButtons.OK, _ MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1) Return False Finally If Not cnn Is Nothing Then cnn.Dispose() End If End Try ' Si llega aqu es que todo ha ido bien Return True End Function
rb1.Checked = False rb2.Checked = False Catch err As Exception MessageBox.Show("Error: " & err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End If epcli.Clear() End If End Sub
MANEJO DE BOTONES
Private Sub btn_first_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTNPRIMERO.Click, BTNANTERIOR.Click, BTNSIGUIENTE.Click, BTNULTIMO.Click If sender Is BTNPRIMERO Then bs.MovePrevious() ElseIf sender Is BTNANTERIOR Then bs.MoveFirst() ElseIf sender Is BTNSIGUIENTE Then bs.MoveNext() ElseIf sender Is BTNULTIMO Then bs.MoveLast() End If End Sub COLOR A LAS CELDAS DEL DATAGRID With DataGridView1 .AlternatingRowsDefaultCellStyle.BackColor = Color.FloralWhite .DefaultCellStyle.BackColor = Color.Beige .DataSource = bs End With FUNCION FECHA
Private Sub btnNuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNuevo.Click Habilitar() Try lblFecha.Text = Date.Now.Date.ToString("yyyy/MM/dd") lblRec.Text = Recibo.ObtenerConsecutivo Catch ex As Exception MessageBox.Show("Error al crear el Nuevo Recibo de Caja." & vbCrLf & ex.Message, "Recibo de Caja", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub GENERAR CODIGO PARA UN RECIBO DE CJA Private Sub btnGenerar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerar.Click If (String.IsNullOrEmpty(txtId.Text)) Then MessageBox.Show("Debe ingresar la informacion del Cliente .", "Recibo de Caja", MessageBoxButtons.OK, MessageBoxIcon.Error) txtId.Focus() End If If (String.IsNullOrEmpty(txtVal.Text)) Then MessageBox.Show("Debe ingresar el Valor del Recibo de Caja.", "Recibo de Caja", MessageBoxButtons.OK, MessageBoxIcon.Error) txtVal.Focus() End If
If (String.IsNullOrEmpty(txtDes.Text)) Then MessageBox.Show("Debe ingresar una Descripcion.", "Recibo de Caja", MessageBoxButtons.OK, MessageBoxIcon.Error) txtDes.Focus() End If Try Recibo.Numero = lblRec.Text Recibo.Fecha = lblFecha.Text Recibo.Cliente = txtId.Text Recibo.Descripcion = txtDes.Text Recibo.Valor = txtVal.Text If (Recibo.Insertar()) Then MessageBox.Show("Recibo de Caja Generado.", "Recibo de Caja", MessageBoxButtons.OK, MessageBoxIcon.Information) Recibo.ActualizarConsecutivo() Imprimir() desHabilitar() Limpiar() End If Catch ex As Exception MessageBox.Show("Error al Generar el Nuevo Recibo de Caja." & vbCrLf & ex.Message, "Recibo de Caja", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub
Archivos planos Sub archivo_plano() Try Dim Delimitador As String = ";" ' ruta del fichero de texto se agrega con el contador mas la extension de texto Dim Archivo_plano As String = "c:\" & Memorando.txtnumero.Text + ".txt" & "" 'Nuevo objeto StreamWriter, para acceder al fichero y poder guardar las lneas Using archivo As StreamWriter = New StreamWriter(Archivo_plano) ' variable para almacenar la lnea actual del dataview Dim linea As String = String.Empty With Memorando.visualizar ' Recorrer las filas del dataGridView For fila As Integer = 0 To .RowCount - 2 ' vaciar la lnea linea = String.Empty ' Recorrer la cantidad de columnas que contiene el dataGridView For col As Integer = 0 To .Columns.Count - 1 ' Almacenar el valor de toda la fila , y cada campo separado por el delimitador linea = linea & .Item(col, fila).Value.ToString & Delimitador Next ' Escribir una lnea con el mtodo WriteLine With archivo ' eliminar el ltimo caracter ";" de la cadena linea = linea.Remove(linea.Length - 1).ToString ' escribir la fila .WriteLine(linea.ToString) End With Next End With End Using Catch ex As Exception
End Sub
End Module
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click 'variable de conexin Dim Con As New MySqlConnection(ConStr) 'variable dataset Dim Ds As New DataSet 'variable tabla Dim Tabla As New DataTable 'adaptador que sirve de enlace intermedio entre la aplicacin y la 'base de datos Dim Da As New MySqlDataAdapter("select * from articulos", Con)
'capturamos errores Try 'ejecutamos la query que tiene el DataAdapter Dim Cmd As New MySqlCommandBuilder(Da) 'llenamos la tabla Da.Fill(Tabla) 'mostramos datos DataGridView1.DataSource = Tabla
Finally
'finalmente eliminamos objetos de memoria Con = Nothing Ds = Nothing Tabla = Nothing Da = Nothing
CUADROS DE DIALOGOS
Dim OpenFileDialog As New OpenFileDialog OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments OpenFileDialog.Filter = "Archivos de texto (*.txt)|*.txt|Todos los archivos (*.*)|*.*" If (OpenFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then Dim FileName As String = OpenFileDialog.FileName ' TODO: agregue cdigo aqu para abrir el archivo. End If
PARA FECHAS
If Me.DGrDat.SelectedCells.Count > 0 Then Dim dia As Integer Dim mes As Integer Dim anio As Integer Dim fechaGrid As String = Me.DGrDat.SelectedCells(9).Value.ToString
dia = Integer.Parse(CStr(Day(CDate(fechaGrid)))) mes = Integer.Parse(CStr(Month(CDate(fechaGrid)))) anio = Integer.Parse(CStr(Year(CDate(fechaGrid)))) 'a Access debo pasarle las fechas en formato: mes-dia-ao
fechaGrid = mes & "/" & dia & "/" & anio
Teclas rapidas
.TECLAS RAPIDAS................ Protected Overrides Sub OnKeyUp(ByVal e As KeyEventArgs) Select Case e.KeyData Case Keys.Escape SALIR() Case Keys.Return, CType(65584, Keys) End Select End Sub End Class