|
Mostrar Mensajes
|
Páginas: 1 [2]
|
11
|
Programación / Ejercicios / Para los q empiezan y quieren practicar
|
en: 18 Marzo 2011, 16:06 pm
|
Realizaremos un ejercio simple de conexión VB~SQL el cual consistira en registrar,modificar y eliminar docentes desde vb _utilizare visual studio 2010 y sql server 2008 _crearemos un nuevo proyecto de tipo formulario windows aki la interfazhttp://img215.imageshack.us/i/interfazk.jpg/
_Luego mostraremos el codigo en SQL go use master go if(db_id('practicando')is not null) drop database practicando go create database practicando go use practicando go create table docente( dni char(8)primary key, n varchar(30)not null, ape varchar(30)not null, sexo char(1)not null check(sexo='M'or sexo='F'), edad tinyint) go create proc registrar(@dni char(8),@n varchar(30),@ape varchar(30), @sexo char(1),@edad tinyint,@msj varchar(60)output) as begin if(exists(select * from docente where dni=dni )) set @msj ='dni ya existe' ELSE BEGIN insert into docente values(@dni ,@n ,@ape ,@sexo ,@edad ) set @msj ='REGISTRADO OK' END end
_ahora el codigo en Vb Imports System.Data Imports System.Data.SqlClient Public Class Form1 Private con As New SqlConnection("Server=.;DataBase=practicando;Integrated Security=true") Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load rbtm.Checked = True listar() txtregistros.Text = DataGridView1.Rows.Count - 1 lblhora.Text = TimeOfDay End Sub Sub listar() Dim dt As New DataTable Dim da As SqlDataAdapter Try abrir() da = New SqlDataAdapter("select * from docente", con) da.Fill(dt) DataGridView1.DataSource = dt Catch ex As Exception : MsgBox(ex.Message) End Try cerrar() txtregistros.Text = DataGridView1.Rows.Count - 1 End Sub Sub abrir() If con.State = 0 Then con.Open() End Sub Sub cerrar() If con.State = 1 Then con.Close() End Sub Sub limpiar() txtape.Clear() TXTDNI.Clear() txtedad.Clear() txtnom.Clear() rbtm.Checked = True End Sub Private Sub btnregistrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnregistrar.Click Dim cmd As SqlCommand Dim msj As String = "" Try abrir() cmd = New SqlCommand("registrar", con) cmd.CommandType = 4 With cmd.Parameters .AddWithValue("@dni", TXTDNI.Text) .AddWithValue("@n", txtnom.Text) .AddWithValue("@ape", txtape.Text) If rbtm.Checked = True Then .AddWithValue("@sexo", "M") Else .AddWithValue("@sexo", "F") End If .AddWithValue("@edad", txtedad.Text) .Add("@msj", SqlDbType.VarChar, 60).Direction = 2 End With cmd.ExecuteNonQuery() msj = cmd.Parameters("@msj").Value MessageBox.Show(msj) Catch ex As Exception : MessageBox.Show(ex.Message) End Try cerrar() limpiar() listar() End Sub End Class
Ahora los q quieran hagan los 2 botones mas Tomar en cuenta que los proc de eliminar y modificar son similares al registrar
|
|
|
12
|
Programación / Java / Re: Otra forma de conectar java~sql
|
en: 18 Marzo 2011, 00:53 am
|
Lo que pasa es q tengo un trabajo dejado por mi profesor que consiste en crear una aplicacion ya sea formularios java o web Jsp con conexion a base datos(SQL) utilizando JNI(Java native interface). yo se conectar formularios web(Jsp) o java con SQL Mediante el ODBC y otros.
_por el momento estoy buscando el instalador JNI _Alguien q me de pistas se lo agradeceria
|
|
|
14
|
Programación / .NET (C#, VB.NET, ASP) / cambiar la forma normal de un formulario a circulo
|
en: 23 Enero 2011, 19:26 pm
|
Ojala les sirva ^^ 1_Abrimos visual studio 2008(es el q utilizo yo), creamos un nuevo proyecto de tipo formulario windows bueno aki la interfaz: 2_AKI el Public Class Form1 Private mouseOffset As Point Private isMouseDown As Boolean = False Button1_Click(boton) Me.Close() 'cierra el formulario End Sub Evento MouseDown Dim xOffset As Integer Dim yOffset As Integer If e.Button = MouseButtons.Left Then xOffset = -e.X - SystemInformation.FrameBorderSize.Width yOffset = -e.Y - SystemInformation.CaptionHeight - _ SystemInformation.FrameBorderSize.Height mouseOffset = New Point(xOffset, yOffset) isMouseDown = True End If End Sub Evento MouseMove If isMouseDown Then Dim mousePos As Point = Control.MousePosition mousePos.Offset(mouseOffset.X, mouseOffset.Y) Location = mousePos End If End Sub Evento MouseUp del formulario If e.Button = MouseButtons.Left Then isMouseDown = False End If End Sub Protected Overrides Sub OnPaint( _ ByVal e As System.Windows.Forms.PaintEventArgs) Dim shape As New System.Drawing.Drawing2D.GraphicsPath shape.AddEllipse(0, 0, Me.Width, Me.Height) Me.Region = New System.Drawing.Region(shape) End Sub End Class
bUENO asi +o - kedaria al ejecutarlo: FaciLiT0
|
|
|
15
|
Programación / .NET (C#, VB.NET, ASP) / Generar y Sumar matrices Dejen comentarios ...
|
en: 23 Enero 2011, 19:01 pm
|
1_Bueno aki les presento un ejercicio simple de como generar y sumar matrices 2_Utilizare visual studio 2008 (creamos un nueco proyecto de tipo Formulario windows) 3_Aki la interfaz :4:aki el Public Class frmsuma 'declaramos variables privadas Private m As Integer(,) Private m2 As Integer(,) Private m3 As Integer(,) Button1 ReDim m(2, 2) 'redimensionamos una matriz de 3*3 ReDim m2(2, 2) ReDim m3(2, 2) Dim fil, col As Integer Dim r As New Random 'generamos la matriz For fil = 0 To 2 For col = 0 To 2 m(fil, col) = r.Next(10, 15) m2(fil, col) = r.Next(5, 20) Next Next 'mostramos la matriz en el listview lvw1.Items.Clear() 'clear para q limpie la lista cada ves q generamos lvw2.Items.Clear() 'clear para q limpie la lista cada ves q generamos lvw3.Items.Clear() 'clear para q limpie la lista cada ves q generamos For fil = 0 To 2 lvw1.Items.Add(m(fil, 0)) lvw2.Items.Add(m2(fil, 0)) For col = 0 To 2 lvw1.Items(fil).SubItems.Add(m(fil, col)) lvw2.Items(fil).SubItems.Add(m(fil, col)) Next Next lvw3.Items.Clear() End Sub ==aki code del btnsm Dim fil, col As Integer For fil = 0 To 2 For col = 0 To 2 m3(fil, col) = m(fil, col) + m2(fil, col) Next Next lvw3.Items.Clear() For fil = 0 To 2 lvw3.Items.Add(m3(fil, 0)) For col = 0 To 2 lvw3.Items(fil).SubItems.Add(m3(fil, col)) Next Next End Class
_Ojala les sirva
|
|
|
16
|
Programación / .NET (C#, VB.NET, ASP) / Visual~Sql===Logeo y llevar el valor de 1 variable a otro formulario
|
en: 21 Enero 2011, 20:59 pm
|
Bueno este es mi 4 post aver si les interesa este ejercicio de logeo con conexión a sql abrimos sql server 2008 y creamos una ew query y aplicamos el siguiente : go use master go if (DB_ID('tienda')is not null) drop database tienda go create database tienda go use tienda go sp_helpdb tienda go create table users (dni char(8)primary key, clave varchar(8)not null, ape varchar(30)not null, nom varchar(30)not null) go --------------------procedimiento loguear create proc loguear(@dni char(8),@clave varchar(8),@datos varchar(62)output) as begin if(exists(select * from users where dni=@dni and clave=@clave )) set @datos =(select ape +','+nom from users where dni=@dni ) else set @datos ='datos incorrectos' end go insert users values('10203040','myPass','Rios flores','Jose'), ('44556677','asd123','Paz gomes','Cinthia') go declare @datos varchar(62) exec loguear '10203040','myPass',@datos output select @datos go declare @datos varchar(62) exec loguear '44556677','asd123',@datos output select @datos go
2_abrimos visual studio 2008 y creamos un new project(formulario windows) 2.1_ le agregamos un modulo con el siguiente: ] Imports System.Data Imports System.Data.SqlClient Module Module1 Public Con As New SqlConnection("Data Source=.;DataBase=tienda;Integrated Security=true") Public Sub abrir() If Con.State = 0 Then Con.Open() End Sub Sub cerrar() If Con.State = 1 Then Con.Close() End Sub Public clave As String End Module
3_ver interfaz del formulario utilizaremos 2 botones y 2 textbox (txtdni-txtclave) y escribimos el siguiente ] Imports System.Data Imports System.Data.SqlClient Public Class acceso Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click ingresar() txtdni.Text = "" txtclave.Text = "" End Sub Sub ingresar() Dim cmd As SqlCommand Dim msj As String Try Call abrir() cmd = New SqlCommand("loguear", Con) cmd.CommandType = CommandType.StoredProcedure With cmd.Parameters .AddWithValue("@dni", txtdni.Text) .AddWithValue("@clave", txtclave.Text) .Add("@datos", SqlDbType.VarChar, 62).Direction = 2 End With cmd.ExecuteNonQuery() msj = cmd.Parameters("@datos").Value MessageBox.Show(msj) clave = cmd.Parameters("@datos").Value Me.Hide() My.Forms.accesoactivo.ShowDialog() Catch ex As Exception MessageBox.Show(ex.Message) End Try Call cerrar() End Sub End Class
4_ahora agregamos un nuevo formulario llamado accesoactivo y aplicamos el siguiente. pero antes vemos la interfaz:(utilizando un toolstrip1 y le agregamos un toolstriptextbox1 llamado ttxtdatos(propiedad name)) ] Imports System.Data Imports System.Data.SqlClient Public Class accesoactivo Private Sub accesoactivo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ttxtdatos.Text = clave End Sub End Class
-Listo . hemos terminado de hacer un logeo con BD . _Despues de logearnos aparecera el nombre del dueño del dni en el ttxtdatos _dni y pass estan en la BD (select * from users) _bueno es todo ojala les sirva
|
|
|
17
|
Programación / .NET (C#, VB.NET, ASP) / Ejemplo visual (fondo mobible-aleatorio imagenes-texto personalizado)
|
en: 21 Enero 2011, 20:23 pm
|
Utilizaremos visual studio 2008 creamos un new project de tipo formulario windows 1_creamos la interfaz . utilizamos radios button(cambiamos su propiedad name y le ponemos (optwin,optball,opttext))respectivamente 2_APlicamos en siguiente Imports System.Drawing.Drawing2D Imports System.Drawing.Text Public Class Form2 Const WinkTimerInterval As Integer = 150 ' En milisegundos Protected eyeImages(6) As Image Protected currentImage As Integer = 0 Protected animationStep As Integer = 1 Const BallTimerInterval As Integer = 25 ' En milisegundos Private ballSize As Integer = 16 ' Como una fracción del área de cliente Private moveSize As Integer = 4 ' Como una fracción del tamaño de la pelota Private bitmap As Bitmap Private ballPositionX As Integer Private ballPositionY As Integer Private ballRadiusX As Integer Private ballRadiusY As Integer Private ballMoveX As Integer Private ballMoveY As Integer Private ballBitmapWidth As Integer Private ballBitmapHeight As Integer Private bitmapWidthMargin As Integer Private bitmapHeightMargin As Integer Const TextTimerInterval As Integer = 15 ' En milisegundos Protected currentGradientShift As Integer = 10 Protected gradiantStep As Integer = 5 Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load eyeImages(0) = My.Resources.dorita eyeImages(1) = My.Resources.bwall58 eyeImages(2) = My.Resources.dorita eyeImages(3) = My.Resources.aioros eyeImages(4) = My.Resources.assasain eyeImages(5) = My.Resources.bwall58 End Sub Private Sub exitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exitToolStripMenuItem.Click Me.Close() End Sub Private Sub optWink_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optWink.CheckedChanged If optWink.Checked Then tmrAnimation.Interval = WinkTimerInterval ElseIf optBall.Checked Then tmrAnimation.Interval = BallTimerInterval ElseIf optText.Checked Then tmrAnimation.Interval = TextTimerInterval End If OnResize(EventArgs.Empty) End Sub Private Sub optBall_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optBall.CheckedChanged If optWink.Checked Then tmrAnimation.Interval = WinkTimerInterval ElseIf optBall.Checked Then tmrAnimation.Interval = BallTimerInterval ElseIf optText.Checked Then tmrAnimation.Interval = TextTimerInterval End If OnResize(EventArgs.Empty) End Sub Protected Overrides Sub OnResize(ByVal ea As EventArgs) If optWink.Checked Then ' Obtenga el objeto Graphics expuesto por el formulario y borre todos los dibujos. Dim grfx As Graphics = CreateGraphics() ' También puede llamar a grfx.Clear(BackColor) o Me.Invalidate() para borrar ' la pantalla. Me.Refresh() grfx.Dispose() ElseIf optBall.Checked Then ' Obtenga el objeto Graphics expuesto por el formulario y borre todos los dibujos. Dim grfx As Graphics = CreateGraphics() grfx.Clear(BackColor) ' Defina el radio de la pelota en una fracción del ancho o el alto ' del área de cliente, el que sea menor. Dim dblRadius As Double = Math.Min(ClientSize.Width / grfx.DpiX, _ ClientSize.Height / grfx.DpiY) / ballSize ' Defina el ancho y el alto de la pelota, ya que normalmente el DPI es ' idéntico en los ejes X e Y. ballRadiusX = CInt(dblRadius * grfx.DpiX) ballRadiusY = CInt(dblRadius * grfx.DpiY) grfx.Dispose() ' Defina la distancia que recorre la pelota en 1 píxel o en una fracción del ' tamaño de la pelota, lo que sea mayor. De esta forma, la distancia que ' recorre la pelota cada vez que se dibuja será proporcional a su tamaño que, ' a su vez, será proporcional al tamaño del área de cliente. Por tanto, cuando ' el área de cliente se reduce, disminuye la velocidad de la pelota, y cuando ' aumenta, se incrementa la velocidad de la pelota. ballMoveX = CInt(Math.Max(1, ballRadiusX / moveSize)) ballMoveY = CInt(Math.Max(1, ballRadiusY / moveSize)) 'Observe que el valor del movimiento de la pelota sirve también como ' margen en torno a la pelota, que determina el tamaño del mapa de bits ' real en el que se dibuja la pelota. Por tanto, la distancia recorrida por la pelota ' es exactamente igual al tamaño del mapa de bits, lo que permite borrar ' la imagen anterior de la pelota antes de que se dibuje la siguiente imagen, y ' todo ello sin que se produzca un parpadeo excesivo. bitmapWidthMargin = ballMoveX bitmapHeightMargin = ballMoveY ' Determine el tamaño real del mapa de bits en el que se dibuja la pelota ' agregando los márgenes a las dimensiones de la pelota. ballBitmapWidth = 2 * (ballRadiusX + bitmapWidthMargin) ballBitmapHeight = 2 * (ballRadiusY + bitmapHeightMargin) ' Cree un nuevo mapa de bits pasando el ancho y el alto bitmap = New Bitmap(ballBitmapWidth, ballBitmapHeight) ' Obtenga el objeto Graphics expuesto por el mapa de bits, limpie la pelota ' existente y dibuje la nueva pelota. grfx = Graphics.FromImage(bitmap) With grfx .Clear(BackColor) .FillEllipse(Brushes.Red, New Rectangle(ballMoveX, _ ballMoveY, 2 * ballRadiusX, 2 * ballRadiusY)) .Dispose() End With ' Restablezca la posición de la pelota en el centro del área de cliente. ballPositionX = CInt(ClientSize.Width / 2) ballPositionY = CInt(ClientSize.Height / 2) ElseIf optText.Checked Then ' Obtenga el objeto Graphics expuesto por el formulario y borre todos los dibujos. Dim grfx As Graphics = CreateGraphics() grfx.Clear(BackColor) End If End Sub Private Sub tmrAnimation_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrAnimation.Tick If optWink.Checked Then ' Obtenga el objeto Graphics expuesto por el formulario. Dim grfx As Graphics = CreateGraphics() ' Llame a DrawImage, mediante Overload #8, que obtiene la imagen actual para su ' presentación, las coordenadas X e Y (que, en este caso, centra la ' imagen en el área de cliente) y el ancho y alto de la imagen. grfx.DrawImage(eyeImages(currentImage), _ CInt((ClientSize.Width - eyeImages(currentImage).Width) / 2), _ CInt((ClientSize.Height - eyeImages(currentImage).Height) / 2), _ eyeImages(currentImage).Width, _ eyeImages(currentImage).Height) ' Es aconsejable que siempre se llame a Dispose para los objetos que exponen este ' método, en lugar de esperar a que el recolector de elementos no utilizados se ejecute automáticamente. ' De esta forma, obtendrá siempre un mayor rendimiento de la aplicación. grfx.Dispose() ' Recorra en bucle las imágenes. currentImage += animationStep If currentImage = 5 Then ' Ésta es la última imagen de las cuatro, por lo que debe invertir el orden de ' animación . animationStep = -1 ElseIf currentImage = 0 Then ' Ésta es la primera imagen , por lo que debe invertir el orden de ' animación animationStep = 1 End If ElseIf optBall.Checked Then ' Obtenga el objeto Graphics expuesto por el formulario. Dim grfx As Graphics = CreateGraphics() ' Dibuje el mapa de bits que contiene la pelota en el formulario. grfx.DrawImage(bitmap, _ CInt(ballPositionX - ballBitmapWidth / 2), _ CInt(ballPositionY - ballBitmapHeight / 2), _ ballBitmapWidth, ballBitmapHeight) grfx.Dispose() ' Aumente la posición de la pelota en la distancia que se ha ' movido en las coordenadas X e Y después de haber sido redibujada. ballPositionX += ballMoveX ballPositionY += ballMoveY ' Invierta la dirección de la pelota cuando toque un extremo. If ballPositionX + ballRadiusX >= ClientSize.Width _ Or ballPositionX - ballRadiusX <= 0 Then ballMoveX = -ballMoveX Beep() End If ' Defina el extremo Y en 80 en lugar de en 0 para que la pelota no rebote ' en los controles del formulario. If ballPositionY + ballRadiusY >= ClientSize.Height _ Or ballPositionY - ballRadiusY <= 80 Then ballMoveY = -ballMoveY Beep() End If ElseIf optText.Checked Then ' Obtenga el objeto Graphics expuesto por el formulario. Dim grfx As Graphics = CreateGraphics() ' Defina el tipo de fuente, el texto y determine su tamaño. Dim font As New Font("Microsoft Sans Serif", 96, _ FontStyle.Bold, GraphicsUnit.Point) Dim strText As String = "Javier_Vidarte_Delgado " Dim sizfText As New SizeF(grfx.MeasureString(strText, font)) ' Defina el punto en el que se va a dibujar el texto: centrado ' en el área de cliente. Dim ptfTextStart As New PointF( _ CSng(ClientSize.Width - sizfText.Width) / 2, _ CSng(ClientSize.Height - sizfText.Height) / 2) ' Defina el punto inicial y final de inclinación; este último se ajustará ' mediante un valor cambiante para producir el efecto de animación. Dim ptfGradientStart As New PointF(0, 0) Dim ptfGradientEnd As New PointF(currentGradientShift, 200) ' Cree una instancia del pincel utilizado para dibujar el texto. Dim grBrush As New LinearGradientBrush(ptfGradientStart, _ ptfGradientEnd, Color.Blue, BackColor) ' Dibuje el texto centrado en el área de cliente. grfx.DrawString(strText, font, grBrush, ptfTextStart) grfx.Dispose() ' Mueva la inclinación e inviértala cuando obtenga un determinado valor. currentGradientShift += gradiantStep If currentGradientShift = 500 Then gradiantStep = -5 ElseIf currentGradientShift = -50 Then gradiantStep = 5 End If End If End Sub End Class
|
|
|
18
|
Programación / .NET (C#, VB.NET, ASP) / Tiburon de numeros aleatorios
|
en: 20 Enero 2011, 23:12 pm
|
este es mi 2 post aver si les interesa utilizaremos el programa visual studio 2008. 1 creamos un new project (de tipo windows form) y creamos la interfaz2 en el boton el siguiente codigo Dim aleatorio As Integer() Dim r As New Random ReDim aleatorio(2) 'asignando valores For i As Integer = 0 To aleatorio.Length - 1 aleatorio(i) = r.Next(1, 5) TextBox1.Text = aleatorio(i) Next For j As Integer = 0 To aleatorio.Length - 1 aleatorio(j) = r.Next(1, 5) TextBox2.Text = aleatorio(j) TextBox1.Text = aleatorio(j) Next For k As Integer = 0 To aleatorio.Length - 1 aleatorio(k) = r.Next(1, 5) TextBox3.Text = aleatorio(k) If TextBox2.Text = aleatorio(k) Then MessageBox.Show("ganastes") End If Next
|
|
|
19
|
Programación / .NET (C#, VB.NET, ASP) / simple ejemplo ;) sql~visual
|
en: 20 Enero 2011, 22:12 pm
|
Bueno soy nuevo en este foro asi k aki les dejo algo ojala les interese utilizamos sql server 2008 .creamos una nueva query y escribimos el siguiente codigoGO USE master GO SET LANGUAGE spanish GO IF(DB_ID('ejemplo')IS NOT NULL) DROP DATABASE ejemplo GO CREATE DATABASE ejemplo GO USE ejemplo GO CREATE TABLE individuo (dni CHAR(8) PRIMARY KEY, apellidos VARCHAR(30) NOT NULL, nombre VARCHAR(30) NOT NULL, sexo CHAR(1) NOT NULL CHECK (sexo IN('M','F')), fecnac DATE NOT NULL, edad tinyint NOT NULL, salario money) GO CREATE proc registrar(@dni CHAR(8), @ape VARCHAR(30), @n VARCHAR(30), @s CHAR(1), @fn DATE, @e tinyint, @sueldo money, @msj VARCHAR(60)output) AS BEGIN IF(NOT EXISTS(SELECT * FROM individuo WHERE dni =@dni )) BEGIN INSERT INTO individuo VALUES(@dni,@ape,@n,@s,@fn,@e,@sueldo) SET @msj ='REGISTRADO' END ELSE --NO EXISTE UNA PERSONA CON EL MISMO DNI SET @msj ='DNI YA EXISTE' END GO CREATE proc modificar(@dni CHAR(8), @ape VARCHAR(30), @n VARCHAR(30), @s CHAR(1), @fn DATE, @e tinyint, @sueldo money, @msj VARCHAR(60)output) AS BEGIN IF(EXISTS(SELECT * FROM individuo WHERE dni =@dni )) BEGIN UPDATE individuo SET apellidos =@ape ,nombre =@n ,sexo =@s ,fecnac =@fn ,edad =@e ,salario =@sueldo WHERE dni =@dni SET @msj ='Datos modificados' END ELSE SET @msj ='DNI no existe' END GO CREATE proc eliminar(@dni CHAR(8),@msj VARCHAR(60)output) AS BEGIN IF(EXISTS(SELECT * FROM individuo WHERE dni =@dni )) BEGIN DELETE FROM individuo WHERE dni =@dni SET @msj ='Datos eliminados' END ELSE SET @msj ='DNI no existe' END
2_despues de haber hecho el code en sql pasamos a visual 2.1_creamos un nuevo proyecto de tipo solucion(otros tipo de proyecto) http://img143.imageshack.us/i/53607601.jpg/
2.2_siguiendo nos vamos a herramientas (proyectos y soluciones-general-activamos mostrar solucion siempre) http://img828.imageshack.us/i/21239949.jpg/
2.3_le damos anticlik ala solucion y agregar nuevo proyecto de tipo biblioteca de clases.(le pondremos por nombre biblioteca)por defecto aparecera una clase ya creada(utilizaremos mas adelante) http://img203.imageshack.us/i/85722103.jpg/ http://img573.imageshack.us/i/95876910.jpg/
2.4_hacemos lo mismo del paso 2.3 pero esta ves creamos una aplicacion de windows forms llamada formularios http://img713.imageshack.us/i/38902831.jpg/
2.5_le damos anticlik a biblioteca (agregar ->modulo)y aplicamos el siguiente code
Imports System.Data Imports System.Data.SqlClient Module Module1 Public con As New SqlConnection("Data Source=.;DataBase=ejemplo;Integrated Security=true") Public Sub abrir() If con.State = 0 Then con.Open() End Sub Public Sub cerrar() If con.State = 1 Then con.Close() End Sub End Module
2.6_ahora le damos anticlik ala solucion y propiedades escogemos como proyecto de inicio formularios http://img200.imageshack.us/i/82265367.jpg/2.7_le agregamos referencia (anticlik a formularios-agregar referencia.proyectos-boblioteca(unika opcion))y aceptar http://img256.imageshack.us/i/20827082.jpg/2.8_entramos a clase 1 escribiremos el code para manejar los procedimientos (registrar-modificar-eliminar)de la BD Imports System.Data Imports System.Data.SqlClient Public Class Class1 Private m_dni, m_ape, m_n, m_s As String Private m_fn As Date Private m_edad As Integer Private m_sueldo As Decimal Public Property dni() As String Get Return m_dni End Get Set(ByVal value As String) m_dni = value End Set End Property Public Property ape() As String Get Return m_ape End Get Set(ByVal value As String) m_ape = value End Set End Property Public Property n() As String Get Return m_n End Get Set(ByVal value As String) m_n = value End Set End Property Public Property s() As String Get Return m_s End Get Set(ByVal value As String) m_s = value End Set End Property Public Property fn() As Date Get Return m_fn End Get Set(ByVal value As Date) m_fn = value End Set End Property Public Property edad() As Integer Get Return m_edad End Get Set(ByVal value As Integer) m_edad = value End Set End Property Public Property sueldo() As Decimal Get Return m_sueldo End Get Set(ByVal value As Decimal) m_sueldo = value End Set End Property Public Function listado() Dim dt As New DataTable Dim da As SqlDataAdapter Try abrir() da = New SqlDataAdapter("select *from individuo", con) da.Fill(dt) Catch ex As Exception : Throw ex End Try cerrar() Return dt End Function Public Function registrar() As String Dim msj As String Dim cmd As SqlCommand Try '@dni,@idt ,@ape,@nom,@sex,@fn,@fi,@fono,@est abrir() cmd = New SqlCommand("registrar", con) cmd.CommandType = CommandType.StoredProcedure With cmd.Parameters cmd.Parameters.AddWithValue("@dni", dni) cmd.Parameters.AddWithValue("@ape", ape) cmd.Parameters.AddWithValue("@n", n) cmd.Parameters.AddWithValue("@s", s) cmd.Parameters.AddWithValue("@fn", fn) cmd.Parameters.AddWithValue("@e", edad) cmd.Parameters.AddWithValue("@sueldo", sueldo) cmd.Parameters.Add("@msj", SqlDbType.VarChar, 30).Direction = ParameterDirection.Output cmd.ExecuteNonQuery() msj = cmd.Parameters("@msj").Value End With Catch ex As Exception : Throw ex End Try cerrar() Return msj End Function Public Function modificar() As String Dim msj As String Dim cmd As SqlCommand Try '@dni,@idt ,@ape,@nom,@sex,@fn,@fi,@fono,@est abrir() cmd = New SqlCommand("modificar", con) cmd.CommandType = CommandType.StoredProcedure With cmd.Parameters cmd.Parameters.AddWithValue("@dni", dni) cmd.Parameters.AddWithValue("@ape", ape) cmd.Parameters.AddWithValue("@n", n) cmd.Parameters.AddWithValue("@s", s) cmd.Parameters.AddWithValue("@fn", fn) cmd.Parameters.AddWithValue("@e", edad) cmd.Parameters.AddWithValue("@sueldo", sueldo) cmd.Parameters.Add("@msj", SqlDbType.VarChar, 30).Direction = ParameterDirection.Output cmd.ExecuteNonQuery() msj = cmd.Parameters("@msj").Value End With Catch ex As Exception : Throw ex End Try cerrar() Return msj End Function Public Function eliminar() As String Dim msj As String Dim cmd As SqlCommand Try '@dni,@idt ,@ape,@nom,@sex,@fn,@fi,@fono,@est abrir() cmd = New SqlCommand("eliminar", con) cmd.CommandType = CommandType.StoredProcedure With cmd.Parameters cmd.Parameters.AddWithValue("@dni", dni) cmd.Parameters.Add("@msj", SqlDbType.VarChar, 30).Direction = ParameterDirection.Output cmd.ExecuteNonQuery() msj = cmd.Parameters("@msj").Value End With Catch ex As Exception : Throw ex End Try cerrar() Return msj End Function End Class
2.9 _despues de haber hecho lo anterior nos vamos al formulario(acomodar la interfaz)Y ESCRIBIMOS EL CODE http://img41.imageshack.us/i/81843289.jpg/
Imports biblioteca Public Class Form1 Public p As New biblioteca.Class1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load listado() RadioButton1.Checked = True End Sub Sub listado() Try DataGridView1.DataSource = p.listado() Catch ex As Exception : MessageBox.Show(ex.Message) End Try End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try p.dni = TextBox1.Text p.ape = TextBox2.Text p.n = TextBox3.Text If RadioButton1.Checked = True Then p.s = "M" Else p.s = "F" End If p.fn = DateTimePicker1.Value p.edad = TextBox4.Text p.sueldo = TextBox5.Text MessageBox.Show(p.registrar()) Catch ex As Exception : MessageBox.Show(ex.Message) End Try listado() limpiar() End Sub Sub limpiar() TextBox1.Clear() TextBox2.Clear() TextBox3.Clear() TextBox4.Clear() TextBox1.ReadOnly = False TextBox5.Clear() DateTimePicker1.Value = Now RadioButton1.Checked = True TextBox1.Focus() End Sub Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged Dim ed As Integer ed = Now.Year - DateTimePicker1.Value.Year TextBox4.Text = ed End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Try p.dni = TextBox1.Text p.ape = TextBox2.Text p.n = TextBox3.Text If RadioButton1.Checked = True Then p.s = "M" Else p.s = "F" End If p.fn = DateTimePicker1.Value p.edad = TextBox4.Text p.sueldo = TextBox5.Text MessageBox.Show(p.modificar()) Catch ex As Exception : MessageBox.Show(ex.Message) End Try listado() limpiar() End Sub Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click Try p.dni = TextBox1.Text MessageBox.Show(p.eliminar()) Catch ex As Exception : MessageBox.Show(ex.Message) End Try listado() limpiar() End Sub Private Sub DataGridView1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataGridView1.Click Try Dim fila As Integer = DataGridView1.CurrentRow.Index With DataGridView1.Rows(fila) TextBox1.Text = .Cells(0).Value.ToString TextBox2.Text = .Cells(1).Value.ToString TextBox3.Text = .Cells(2).Value.ToString If .Cells(3).Value.ToString = "M" Then RadioButton1.Checked = True Else RadioButton2.Checked = True End If DateTimePicker1.Value = .Cells(4).Value.ToString TextBox4.Text = .Cells(5).Value.ToString TextBox5.Text = .Cells(6).Value.ToString End With TextBox1.ReadOnly = True Catch ex As Exception : MessageBox.Show("fila sin datos") End Try End Sub End Class
nota: UTILIZAMOS PROCEDIMIENTOS ,Funciones,Parametros de salida(output) PARA BUSCAR LOS DATOS SOLO DA CLIK EN CUALQUIERA CELDA . PARA LIMPIAR LAS CAJAS AGREGA UN LINKLABEL (LE AGREGAS EL CODE(limpiar))
saludos : ojala les sirvaNota del Moderador: Por favor, existe la etiqueta Code, la cual puedes usar sin ningún problema.Gracias.
|
|
|
|
|
|
|