elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Guía rápida para descarga de herramientas gratuitas de seguridad y desinfección


  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 interfaz


http://img215.imageshack.us/i/interfazk.jpg/


_Luego mostraremos el codigo en SQL
 
Código
  1.  
  2. go
  3. use master
  4. go
  5. if(db_id('practicando')is not null)
  6. drop database practicando
  7. go
  8. create database practicando
  9. go
  10. use practicando
  11. go
  12. create table docente(
  13. dni char(8)primary key,
  14. n varchar(30)not null,
  15. ape varchar(30)not null,
  16. sexo char(1)not null check(sexo='M'or sexo='F'),
  17. edad tinyint)
  18. go
  19. create proc registrar(@dni char(8),@n varchar(30),@ape varchar(30),
  20. @sexo char(1),@edad tinyint,@msj varchar(60)output)
  21. as begin
  22. if(exists(select * from docente where dni=dni ))
  23. set @msj ='dni ya existe'
  24. ELSE
  25. BEGIN
  26. insert into docente values(@dni ,@n ,@ape ,@sexo ,@edad )
  27. set @msj ='REGISTRADO OK'
  28. END
  29. end
  30.  


_ahora el codigo en Vb

 
Código
  1.  
  2. Imports System.Data
  3. Imports System.Data.SqlClient
  4. Public Class Form1
  5.    Private con As New SqlConnection("Server=.;DataBase=practicando;Integrated Security=true")
  6.    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  7.        rbtm.Checked = True
  8.        listar()
  9.        txtregistros.Text = DataGridView1.Rows.Count - 1
  10.        lblhora.Text = TimeOfDay
  11.    End Sub
  12.    Sub listar()
  13.        Dim dt As New DataTable
  14.        Dim da As SqlDataAdapter
  15.        Try
  16.            abrir()
  17.            da = New SqlDataAdapter("select * from docente", con)
  18.            da.Fill(dt)
  19.            DataGridView1.DataSource = dt
  20.        Catch ex As Exception : MsgBox(ex.Message)
  21.        End Try
  22.        cerrar()
  23.        txtregistros.Text = DataGridView1.Rows.Count - 1
  24.    End Sub
  25.    Sub abrir()
  26.        If con.State = 0 Then con.Open()
  27.    End Sub
  28.    Sub cerrar()
  29.        If con.State = 1 Then con.Close()
  30.    End Sub
  31.    Sub limpiar()
  32.        txtape.Clear()
  33.        TXTDNI.Clear()
  34.        txtedad.Clear()
  35.        txtnom.Clear()
  36.        rbtm.Checked = True
  37.    End Sub
  38.  
  39.    Private Sub btnregistrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnregistrar.Click
  40.        Dim cmd As SqlCommand
  41.        Dim msj As String = ""
  42.        Try
  43.            abrir()
  44.            cmd = New SqlCommand("registrar", con)
  45.            cmd.CommandType = 4
  46.            With cmd.Parameters
  47.                .AddWithValue("@dni", TXTDNI.Text)
  48.                .AddWithValue("@n", txtnom.Text)
  49.                .AddWithValue("@ape", txtape.Text)
  50.                If rbtm.Checked = True Then
  51.                    .AddWithValue("@sexo", "M")
  52.                Else
  53.                    .AddWithValue("@sexo", "F")
  54.                End If
  55.                .AddWithValue("@edad", txtedad.Text)
  56.                .Add("@msj", SqlDbType.VarChar, 60).Direction = 2
  57.            End With
  58.            cmd.ExecuteNonQuery()
  59.            msj = cmd.Parameters("@msj").Value
  60.            MessageBox.Show(msj)
  61.        Catch ex As Exception : MessageBox.Show(ex.Message)
  62.  
  63.        End Try
  64.        cerrar()
  65.        limpiar()
  66.        listar()
  67.    End Sub
  68. End Class
  69.  

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
13  Programación / Java / Otra forma de conectar java~sql en: 25 Febrero 2011, 18:34 pm
quisiera saber si hay otra forma de conectar java con sql aparte
del ODBC.
Y quisiera saber si CON JNI TAMBIEN SE PUEDE
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

 
Código
  1. Public Class Form1
  2.  
  3.    Private mouseOffset As Point
  4.    Private isMouseDown As Boolean = False
  5.  
  6. Button1_Click(boton)
  7.        Me.Close()
  8.   'cierra el formulario
  9.    End Sub
  10.  
  11. Evento MouseDown
  12.  
  13.        Dim xOffset As Integer
  14.        Dim yOffset As Integer
  15.        If e.Button = MouseButtons.Left Then
  16.            xOffset = -e.X - SystemInformation.FrameBorderSize.Width
  17.            yOffset = -e.Y - SystemInformation.CaptionHeight - _
  18.                    SystemInformation.FrameBorderSize.Height
  19.            mouseOffset = New Point(xOffset, yOffset)
  20.            isMouseDown = True
  21.        End If
  22.    End Sub
  23.  
  24. Evento MouseMove
  25.  
  26.        If isMouseDown Then
  27.            Dim mousePos As Point = Control.MousePosition
  28.            mousePos.Offset(mouseOffset.X, mouseOffset.Y)
  29.            Location = mousePos
  30.        End If
  31.    End Sub
  32.  
  33. Evento  MouseUp del formulario
  34.        If e.Button = MouseButtons.Left Then
  35.            isMouseDown = False
  36.        End If
  37.    End Sub
  38.  
  39.    Protected Overrides Sub OnPaint( _
  40.       ByVal e As System.Windows.Forms.PaintEventArgs)
  41.        Dim shape As New System.Drawing.Drawing2D.GraphicsPath
  42.        shape.AddEllipse(0, 0, Me.Width, Me.Height)
  43.        Me.Region = New System.Drawing.Region(shape)
  44.    End Sub
  45.  
  46.  
  47. End Class
  48.  
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

 
Código
  1. Public Class frmsuma
  2.  
  3. 'declaramos variables privadas
  4.    Private m As Integer(,)
  5.    Private m2 As Integer(,)
  6.    Private m3 As Integer(,)
  7.  
  8.  Button1
  9.        ReDim m(2, 2) 'redimensionamos una matriz de 3*3
  10.        ReDim m2(2, 2)
  11.        ReDim m3(2, 2)
  12.        Dim fil, col As Integer
  13.        Dim r As New Random
  14.        'generamos la matriz
  15.        For fil = 0 To 2
  16.            For col = 0 To 2
  17.                m(fil, col) = r.Next(10, 15)
  18.                m2(fil, col) = r.Next(5, 20)
  19.            Next
  20.        Next
  21.        'mostramos la matriz en el listview
  22.        lvw1.Items.Clear() 'clear para q limpie la lista cada ves q generamos
  23.        lvw2.Items.Clear() 'clear para q limpie la lista cada ves q generamos
  24.        lvw3.Items.Clear() 'clear para q limpie la lista cada ves q generamos
  25.        For fil = 0 To 2
  26.            lvw1.Items.Add(m(fil, 0))
  27.            lvw2.Items.Add(m2(fil, 0))
  28.            For col = 0 To 2
  29.                lvw1.Items(fil).SubItems.Add(m(fil, col))
  30.                lvw2.Items(fil).SubItems.Add(m(fil, col))
  31.            Next
  32.        Next
  33.        lvw3.Items.Clear()
  34.    End Sub
  35.  
  36. ==aki code del btnsm
  37.  
  38.        Dim fil, col As Integer
  39.        For fil = 0 To 2
  40.            For col = 0 To 2
  41.                m3(fil, col) = m(fil, col) + m2(fil, col)
  42.            Next
  43.        Next
  44.        lvw3.Items.Clear()
  45.        For fil = 0 To 2
  46.            lvw3.Items.Add(m3(fil, 0))
  47.            For col = 0 To 2
  48.                lvw3.Items(fil).SubItems.Add(m3(fil, col))
  49.            Next
  50.        Next
  51.  
  52. End Class
  53.  
_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 :


 
Código
  1. go
  2. use master
  3. go
  4. if (DB_ID('tienda')is not null)
  5. drop database tienda
  6. go
  7. create database tienda
  8. go
  9. use tienda
  10. go
  11. sp_helpdb tienda
  12. go
  13. create table users
  14. (dni char(8)primary key,
  15. clave varchar(8)not null,
  16. ape varchar(30)not null,
  17. nom varchar(30)not null)
  18. go
  19. --------------------procedimiento loguear
  20. create proc loguear(@dni char(8),@clave varchar(8),@datos varchar(62)output)
  21. as begin
  22. if(exists(select * from users where dni=@dni and clave=@clave ))
  23. set @datos =(select ape +','+nom from users  where dni=@dni )
  24. else
  25. set @datos ='datos incorrectos'
  26. end
  27. go
  28. insert users values('10203040','myPass','Rios flores','Jose'),
  29.                     ('44556677','asd123','Paz gomes','Cinthia')
  30. go
  31. declare @datos varchar(62)
  32. exec loguear '10203040','myPass',@datos output
  33. select @datos
  34. go
  35. declare @datos varchar(62)
  36. exec loguear '44556677','asd123',@datos output
  37. select @datos
  38. go
  39.  
  40.  

2_abrimos visual studio 2008 y creamos un new project(formulario windows)
2.1_ le agregamos un modulo con el siguiente:
  
Código
  1. ]
  2. Imports System.Data
  3. Imports System.Data.SqlClient
  4. Module Module1
  5.    Public Con As New SqlConnection("Data Source=.;DataBase=tienda;Integrated Security=true")
  6.    Public Sub abrir()
  7.        If Con.State = 0 Then Con.Open()
  8.    End Sub
  9.    Sub cerrar()
  10.        If Con.State = 1 Then Con.Close()
  11.  
  12.    End Sub
  13.    Public clave As String
  14. End Module
  15.  


3_ver interfaz del formulario


utilizaremos 2 botones y 2 textbox (txtdni-txtclave) y escribimos el siguiente
Código
  1. ]
  2. Imports System.Data
  3. Imports System.Data.SqlClient
  4. Public Class acceso
  5.    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  6.        ingresar()
  7.        txtdni.Text = ""
  8.        txtclave.Text = ""
  9.    End Sub
  10.    Sub ingresar()
  11.        Dim cmd As SqlCommand
  12.        Dim msj As String
  13.        Try
  14.            Call abrir()
  15.            cmd = New SqlCommand("loguear", Con)
  16.            cmd.CommandType = CommandType.StoredProcedure
  17.            With cmd.Parameters
  18.                .AddWithValue("@dni", txtdni.Text)
  19.                .AddWithValue("@clave", txtclave.Text)
  20.                .Add("@datos", SqlDbType.VarChar, 62).Direction = 2
  21.            End With
  22.            cmd.ExecuteNonQuery()
  23.            msj = cmd.Parameters("@datos").Value
  24.            MessageBox.Show(msj)
  25.            clave = cmd.Parameters("@datos").Value
  26.            Me.Hide()
  27.            My.Forms.accesoactivo.ShowDialog()
  28.        Catch ex As Exception
  29.            MessageBox.Show(ex.Message)
  30.        End Try
  31.        Call cerrar()
  32.    End Sub
  33.  
  34. End Class
  35.  

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))



Código
  1. ]
  2. Imports System.Data
  3. Imports System.Data.SqlClient
  4. Public Class accesoactivo
  5.    Private Sub accesoactivo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  6.        ttxtdatos.Text = clave
  7.    End Sub
  8. End Class
  9.  
-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
Código
  1.  
  2. Imports System.Drawing.Drawing2D
  3. Imports System.Drawing.Text
  4. Public Class Form2
  5.    Const WinkTimerInterval As Integer = 150 ' En milisegundos
  6.    Protected eyeImages(6) As Image
  7.    Protected currentImage As Integer = 0
  8.    Protected animationStep As Integer = 1
  9.    Const BallTimerInterval As Integer = 25 ' En milisegundos
  10.    Private ballSize As Integer = 16 ' Como una fracción del área de cliente
  11.    Private moveSize As Integer = 4 ' Como una fracción del tamaño de la pelota
  12.    Private bitmap As Bitmap
  13.    Private ballPositionX As Integer
  14.    Private ballPositionY As Integer
  15.    Private ballRadiusX As Integer
  16.    Private ballRadiusY As Integer
  17.    Private ballMoveX As Integer
  18.    Private ballMoveY As Integer
  19.    Private ballBitmapWidth As Integer
  20.    Private ballBitmapHeight As Integer
  21.    Private bitmapWidthMargin As Integer
  22.    Private bitmapHeightMargin As Integer
  23.  
  24.    Const TextTimerInterval As Integer = 15 ' En milisegundos
  25.    Protected currentGradientShift As Integer = 10
  26.    Protected gradiantStep As Integer = 5
  27.    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  28.        eyeImages(0) = My.Resources.dorita
  29.        eyeImages(1) = My.Resources.bwall58
  30.        eyeImages(2) = My.Resources.dorita
  31.        eyeImages(3) = My.Resources.aioros
  32.        eyeImages(4) = My.Resources.assasain
  33.        eyeImages(5) = My.Resources.bwall58
  34.    End Sub
  35.  
  36.    Private Sub exitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exitToolStripMenuItem.Click
  37.        Me.Close()
  38.    End Sub
  39.  
  40.    Private Sub optWink_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optWink.CheckedChanged
  41.        If optWink.Checked Then
  42.            tmrAnimation.Interval = WinkTimerInterval
  43.        ElseIf optBall.Checked Then
  44.            tmrAnimation.Interval = BallTimerInterval
  45.        ElseIf optText.Checked Then
  46.            tmrAnimation.Interval = TextTimerInterval
  47.        End If
  48.  
  49.        OnResize(EventArgs.Empty)
  50.    End Sub
  51.  
  52.    Private Sub optBall_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optBall.CheckedChanged
  53.        If optWink.Checked Then
  54.            tmrAnimation.Interval = WinkTimerInterval
  55.        ElseIf optBall.Checked Then
  56.            tmrAnimation.Interval = BallTimerInterval
  57.        ElseIf optText.Checked Then
  58.            tmrAnimation.Interval = TextTimerInterval
  59.        End If
  60.  
  61.        OnResize(EventArgs.Empty)
  62.    End Sub
  63.    Protected Overrides Sub OnResize(ByVal ea As EventArgs)
  64.        If optWink.Checked Then
  65.  
  66.            ' Obtenga el objeto Graphics expuesto por el formulario y borre todos los dibujos.
  67.            Dim grfx As Graphics = CreateGraphics()
  68.            ' También puede llamar a grfx.Clear(BackColor) o Me.Invalidate() para borrar
  69.            ' la pantalla.
  70.            Me.Refresh()
  71.            grfx.Dispose()
  72.  
  73.        ElseIf optBall.Checked Then
  74.  
  75.            ' Obtenga el objeto Graphics expuesto por el formulario y borre todos los dibujos.
  76.            Dim grfx As Graphics = CreateGraphics()
  77.            grfx.Clear(BackColor)
  78.  
  79.            ' Defina el radio de la pelota en una fracción del ancho o el alto
  80.            ' del área de cliente, el que sea menor.
  81.            Dim dblRadius As Double = Math.Min(ClientSize.Width / grfx.DpiX, _
  82.                ClientSize.Height / grfx.DpiY) / ballSize
  83.  
  84.            ' Defina el ancho y el alto de la pelota, ya que normalmente el DPI es
  85.            ' idéntico en los ejes X e Y.
  86.            ballRadiusX = CInt(dblRadius * grfx.DpiX)
  87.            ballRadiusY = CInt(dblRadius * grfx.DpiY)
  88.  
  89.            grfx.Dispose()
  90.  
  91.            ' Defina la distancia que recorre la pelota en 1 píxel o en una fracción del
  92.            ' tamaño de la pelota, lo que sea mayor. De esta forma, la distancia que
  93.            ' recorre la pelota cada vez que se dibuja será proporcional a su tamaño que,
  94.            ' a su vez, será proporcional al tamaño del área de cliente. Por tanto, cuando
  95.            ' el área de cliente se reduce, disminuye la velocidad de la pelota, y cuando
  96.            ' aumenta, se incrementa la velocidad de la pelota.
  97.            ballMoveX = CInt(Math.Max(1, ballRadiusX / moveSize))
  98.            ballMoveY = CInt(Math.Max(1, ballRadiusY / moveSize))
  99.  
  100.            'Observe que el valor del movimiento de la pelota sirve también como
  101.            ' margen en torno a la pelota, que determina el tamaño del mapa de bits
  102.            ' real en el que se dibuja la pelota. Por tanto, la distancia recorrida por la pelota
  103.            ' es exactamente igual al tamaño del mapa de bits, lo que permite borrar
  104.            ' la imagen anterior de la pelota antes de que se dibuje la siguiente imagen, y
  105.            ' todo ello sin que se produzca un parpadeo excesivo.
  106.            bitmapWidthMargin = ballMoveX
  107.            bitmapHeightMargin = ballMoveY
  108.  
  109.            ' Determine el tamaño real del mapa de bits en el que se dibuja la pelota
  110.            ' agregando los márgenes a las dimensiones de la pelota.
  111.            ballBitmapWidth = 2 * (ballRadiusX + bitmapWidthMargin)
  112.            ballBitmapHeight = 2 * (ballRadiusY + bitmapHeightMargin)
  113.  
  114.            ' Cree un nuevo mapa de bits pasando el ancho y el alto
  115.            bitmap = New Bitmap(ballBitmapWidth, ballBitmapHeight)
  116.  
  117.            ' Obtenga el objeto Graphics expuesto por el mapa de bits, limpie la pelota
  118.            ' existente y dibuje la nueva pelota.
  119.            grfx = Graphics.FromImage(bitmap)
  120.            With grfx
  121.                .Clear(BackColor)
  122.                .FillEllipse(Brushes.Red, New Rectangle(ballMoveX, _
  123.                    ballMoveY, 2 * ballRadiusX, 2 * ballRadiusY))
  124.                .Dispose()
  125.            End With
  126.  
  127.            ' Restablezca la posición de la pelota en el centro del área de cliente.
  128.            ballPositionX = CInt(ClientSize.Width / 2)
  129.            ballPositionY = CInt(ClientSize.Height / 2)
  130.  
  131.        ElseIf optText.Checked Then
  132.            ' Obtenga el objeto Graphics expuesto por el formulario y borre todos los dibujos.
  133.            Dim grfx As Graphics = CreateGraphics()
  134.            grfx.Clear(BackColor)
  135.        End If
  136.    End Sub
  137.  
  138.    Private Sub tmrAnimation_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrAnimation.Tick
  139.        If optWink.Checked Then
  140.  
  141.            ' Obtenga el objeto Graphics expuesto por el formulario.
  142.            Dim grfx As Graphics = CreateGraphics()
  143.  
  144.            ' Llame a DrawImage, mediante Overload #8, que obtiene la imagen actual para su
  145.            ' presentación, las coordenadas X e Y (que, en este caso, centra la
  146.            ' imagen en el área de cliente) y el ancho y alto de la imagen.
  147.            grfx.DrawImage(eyeImages(currentImage), _
  148.                CInt((ClientSize.Width - eyeImages(currentImage).Width) / 2), _
  149.                CInt((ClientSize.Height - eyeImages(currentImage).Height) / 2), _
  150.                eyeImages(currentImage).Width, _
  151.                eyeImages(currentImage).Height)
  152.            ' Es aconsejable que siempre se llame a Dispose para los objetos que exponen este
  153.            ' método, en lugar de esperar a que el recolector de elementos no utilizados se ejecute automáticamente.
  154.            ' De esta forma, obtendrá siempre un mayor rendimiento de la aplicación.
  155.            grfx.Dispose()
  156.  
  157.            ' Recorra en bucle las imágenes.
  158.            currentImage += animationStep
  159.            If currentImage = 5 Then
  160.                ' Ésta es la última imagen de las cuatro, por lo que debe invertir el orden de
  161.                ' animación .
  162.                animationStep = -1
  163.            ElseIf currentImage = 0 Then
  164.                ' Ésta es la primera imagen , por lo que debe invertir el orden de
  165.                ' animación
  166.                animationStep = 1
  167.            End If
  168.  
  169.        ElseIf optBall.Checked Then
  170.  
  171.            ' Obtenga el objeto Graphics expuesto por el formulario.
  172.            Dim grfx As Graphics = CreateGraphics()
  173.            ' Dibuje el mapa de bits que contiene la pelota en el formulario.
  174.            grfx.DrawImage(bitmap, _
  175.                CInt(ballPositionX - ballBitmapWidth / 2), _
  176.                CInt(ballPositionY - ballBitmapHeight / 2), _
  177.                ballBitmapWidth, ballBitmapHeight)
  178.  
  179.            grfx.Dispose()
  180.  
  181.            ' Aumente la posición de la pelota en la distancia que se ha
  182.            ' movido en las coordenadas X e Y después de haber sido redibujada.
  183.            ballPositionX += ballMoveX
  184.            ballPositionY += ballMoveY
  185.  
  186.            ' Invierta la dirección de la pelota cuando toque un extremo.
  187.            If ballPositionX + ballRadiusX >= ClientSize.Width _
  188.                Or ballPositionX - ballRadiusX <= 0 Then
  189.                ballMoveX = -ballMoveX
  190.                Beep()
  191.            End If
  192.            ' Defina el extremo Y en 80 en lugar de en 0 para que la pelota no rebote
  193.            ' en los controles del formulario.
  194.            If ballPositionY + ballRadiusY >= ClientSize.Height _
  195.                Or ballPositionY - ballRadiusY <= 80 Then
  196.                ballMoveY = -ballMoveY
  197.                Beep()
  198.            End If
  199.  
  200.        ElseIf optText.Checked Then
  201.  
  202.            ' Obtenga el objeto Graphics expuesto por el formulario.
  203.            Dim grfx As Graphics = CreateGraphics()
  204.  
  205.            ' Defina el tipo de fuente, el texto y determine su tamaño.
  206.            Dim font As New Font("Microsoft Sans Serif", 96, _
  207.                FontStyle.Bold, GraphicsUnit.Point)
  208.            Dim strText As String = "Javier_Vidarte_Delgado "
  209.            Dim sizfText As New SizeF(grfx.MeasureString(strText, font))
  210.  
  211.            ' Defina el punto en el que se va a dibujar el texto: centrado
  212.            ' en el área de cliente.
  213.            Dim ptfTextStart As New PointF( _
  214.                CSng(ClientSize.Width - sizfText.Width) / 2, _
  215.                CSng(ClientSize.Height - sizfText.Height) / 2)
  216.  
  217.            ' Defina el punto inicial y final de inclinación; este último se ajustará
  218.            ' mediante un valor cambiante para producir el efecto de animación.
  219.            Dim ptfGradientStart As New PointF(0, 0)
  220.            Dim ptfGradientEnd As New PointF(currentGradientShift, 200)
  221.  
  222.            ' Cree una instancia del pincel utilizado para dibujar el texto.
  223.            Dim grBrush As New LinearGradientBrush(ptfGradientStart, _
  224.                ptfGradientEnd, Color.Blue, BackColor)
  225.  
  226.            ' Dibuje el texto centrado en el área de cliente.
  227.            grfx.DrawString(strText, font, grBrush, ptfTextStart)
  228.  
  229.            grfx.Dispose()
  230.  
  231.            ' Mueva la inclinación e inviértala cuando obtenga un determinado valor.
  232.            currentGradientShift += gradiantStep
  233.            If currentGradientShift = 500 Then
  234.                gradiantStep = -5
  235.            ElseIf currentGradientShift = -50 Then
  236.                gradiantStep = 5
  237.            End If
  238.        End If
  239.    End Sub
  240. 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 interfaz



2 en el boton el siguiente codigo
Código
  1.        Dim aleatorio As Integer()
  2.        Dim r As New Random
  3.        ReDim aleatorio(2)
  4.        'asignando valores
  5.        For i As Integer = 0 To aleatorio.Length - 1
  6.            aleatorio(i) = r.Next(1, 5)
  7.            TextBox1.Text = aleatorio(i)
  8.        Next
  9.        For j As Integer = 0 To aleatorio.Length - 1
  10.            aleatorio(j) = r.Next(1, 5)
  11.            TextBox2.Text = aleatorio(j)
  12.            TextBox1.Text = aleatorio(j)
  13.        Next
  14.        For k As Integer = 0 To aleatorio.Length - 1
  15.            aleatorio(k) = r.Next(1, 5)
  16.            TextBox3.Text = aleatorio(k)
  17.            If TextBox2.Text = aleatorio(k) Then
  18.                MessageBox.Show("ganastes")
  19.            End If
  20.        Next
  21.  
  22.  
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 codigo


Código
  1. GO
  2. USE master
  3. GO
  4. SET LANGUAGE spanish
  5. GO
  6. IF(DB_ID('ejemplo')IS NOT NULL)
  7. DROP DATABASE ejemplo
  8. GO
  9. CREATE DATABASE ejemplo
  10. GO
  11. USE ejemplo
  12. GO
  13. CREATE TABLE individuo
  14. (dni CHAR(8) PRIMARY KEY,
  15. apellidos VARCHAR(30) NOT NULL,
  16. nombre VARCHAR(30) NOT NULL,
  17. sexo CHAR(1) NOT NULL CHECK (sexo IN('M','F')),
  18. fecnac DATE NOT NULL,
  19. edad tinyint NOT NULL,
  20. salario money)
  21. GO
  22. CREATE proc registrar(@dni CHAR(8),
  23. @ape VARCHAR(30),
  24. @n VARCHAR(30),
  25. @s CHAR(1),
  26. @fn DATE,
  27. @e tinyint,
  28. @sueldo money,
  29. @msj VARCHAR(60)output)
  30. AS BEGIN
  31. IF(NOT EXISTS(SELECT * FROM individuo WHERE dni =@dni ))
  32. BEGIN
  33. INSERT INTO individuo VALUES(@dni,@ape,@n,@s,@fn,@e,@sueldo)
  34. SET @msj ='REGISTRADO'
  35. END
  36. ELSE
  37. --NO EXISTE UNA PERSONA CON EL MISMO DNI
  38. SET @msj ='DNI YA EXISTE'
  39. END
  40. GO
  41. CREATE proc modificar(@dni CHAR(8),
  42. @ape VARCHAR(30),
  43. @n VARCHAR(30),
  44. @s CHAR(1),
  45. @fn DATE,
  46. @e tinyint,
  47. @sueldo money,
  48. @msj VARCHAR(60)output)
  49. AS BEGIN
  50. IF(EXISTS(SELECT * FROM individuo WHERE dni =@dni ))
  51. BEGIN
  52. UPDATE individuo SET apellidos =@ape ,nombre =@n ,sexo =@s ,fecnac =@fn ,edad =@e ,salario =@sueldo WHERE dni =@dni
  53. SET @msj ='Datos modificados'
  54. END
  55. ELSE
  56. SET @msj ='DNI no existe'
  57. END
  58. GO
  59. CREATE proc eliminar(@dni CHAR(8),@msj VARCHAR(60)output)
  60. AS BEGIN
  61. IF(EXISTS(SELECT * FROM individuo WHERE dni =@dni ))
  62. BEGIN
  63. DELETE FROM individuo WHERE dni =@dni
  64. SET @msj ='Datos eliminados'
  65. END
  66. ELSE
  67. SET @msj ='DNI no existe'
  68. END
  69.  

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


Código
  1. Imports System.Data
  2. Imports System.Data.SqlClient
  3. Module Module1
  4.    Public con As New SqlConnection("Data Source=.;DataBase=ejemplo;Integrated Security=true")
  5.    Public Sub abrir()
  6.        If con.State = 0 Then con.Open()
  7.    End Sub
  8.    Public Sub cerrar()
  9.        If con.State = 1 Then con.Close()
  10.    End Sub
  11. End Module
  12.  

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


Código
  1.  
  2. Imports System.Data
  3. Imports System.Data.SqlClient
  4. Public Class Class1
  5.    Private m_dni, m_ape, m_n, m_s As String
  6.    Private m_fn As Date
  7.    Private m_edad As Integer
  8.    Private m_sueldo As Decimal
  9.    Public Property dni() As String
  10.        Get
  11.            Return m_dni
  12.        End Get
  13.        Set(ByVal value As String)
  14.            m_dni = value
  15.        End Set
  16.    End Property
  17.    Public Property ape() As String
  18.        Get
  19.            Return m_ape
  20.        End Get
  21.        Set(ByVal value As String)
  22.            m_ape = value
  23.        End Set
  24.    End Property
  25.    Public Property n() As String
  26.        Get
  27.            Return m_n
  28.        End Get
  29.        Set(ByVal value As String)
  30.            m_n = value
  31.        End Set
  32.    End Property
  33.    Public Property s() As String
  34.        Get
  35.            Return m_s
  36.        End Get
  37.        Set(ByVal value As String)
  38.            m_s = value
  39.        End Set
  40.    End Property
  41.    Public Property fn() As Date
  42.        Get
  43.            Return m_fn
  44.        End Get
  45.        Set(ByVal value As Date)
  46.            m_fn = value
  47.        End Set
  48.    End Property
  49.    Public Property edad() As Integer
  50.        Get
  51.            Return m_edad
  52.        End Get
  53.        Set(ByVal value As Integer)
  54.            m_edad = value
  55.        End Set
  56.    End Property
  57.    Public Property sueldo() As Decimal
  58.        Get
  59.            Return m_sueldo
  60.        End Get
  61.        Set(ByVal value As Decimal)
  62.            m_sueldo = value
  63.        End Set
  64.    End Property
  65.    Public Function listado()
  66.        Dim dt As New DataTable
  67.        Dim da As SqlDataAdapter
  68.        Try
  69.            abrir()
  70.            da = New SqlDataAdapter("select *from individuo", con)
  71.            da.Fill(dt)
  72.        Catch ex As Exception : Throw ex
  73.        End Try
  74.        cerrar()
  75.        Return dt
  76.    End Function
  77.    Public Function registrar() As String
  78.        Dim msj As String
  79.        Dim cmd As SqlCommand
  80.        Try
  81.            '@dni,@idt ,@ape,@nom,@sex,@fn,@fi,@fono,@est
  82.            abrir()
  83.            cmd = New SqlCommand("registrar", con)
  84.            cmd.CommandType = CommandType.StoredProcedure
  85.            With cmd.Parameters
  86.                cmd.Parameters.AddWithValue("@dni", dni)
  87.                cmd.Parameters.AddWithValue("@ape", ape)
  88.                cmd.Parameters.AddWithValue("@n", n)
  89.                cmd.Parameters.AddWithValue("@s", s)
  90.                cmd.Parameters.AddWithValue("@fn", fn)
  91.                cmd.Parameters.AddWithValue("@e", edad)
  92.                cmd.Parameters.AddWithValue("@sueldo", sueldo)
  93.                cmd.Parameters.Add("@msj", SqlDbType.VarChar, 30).Direction = ParameterDirection.Output
  94.                cmd.ExecuteNonQuery()
  95.                msj = cmd.Parameters("@msj").Value
  96.            End With
  97.        Catch ex As Exception : Throw ex
  98.        End Try
  99.        cerrar()
  100.        Return msj
  101.    End Function
  102.    Public Function modificar() As String
  103.        Dim msj As String
  104.        Dim cmd As SqlCommand
  105.        Try
  106.            '@dni,@idt ,@ape,@nom,@sex,@fn,@fi,@fono,@est
  107.            abrir()
  108.            cmd = New SqlCommand("modificar", con)
  109.            cmd.CommandType = CommandType.StoredProcedure
  110.            With cmd.Parameters
  111.                cmd.Parameters.AddWithValue("@dni", dni)
  112.                cmd.Parameters.AddWithValue("@ape", ape)
  113.                cmd.Parameters.AddWithValue("@n", n)
  114.                cmd.Parameters.AddWithValue("@s", s)
  115.                cmd.Parameters.AddWithValue("@fn", fn)
  116.                cmd.Parameters.AddWithValue("@e", edad)
  117.                cmd.Parameters.AddWithValue("@sueldo", sueldo)
  118.                cmd.Parameters.Add("@msj", SqlDbType.VarChar, 30).Direction = ParameterDirection.Output
  119.                cmd.ExecuteNonQuery()
  120.                msj = cmd.Parameters("@msj").Value
  121.            End With
  122.        Catch ex As Exception : Throw ex
  123.        End Try
  124.        cerrar()
  125.        Return msj
  126.    End Function
  127.    Public Function eliminar() As String
  128.        Dim msj As String
  129.        Dim cmd As SqlCommand
  130.        Try
  131.            '@dni,@idt ,@ape,@nom,@sex,@fn,@fi,@fono,@est
  132.            abrir()
  133.            cmd = New SqlCommand("eliminar", con)
  134.            cmd.CommandType = CommandType.StoredProcedure
  135.            With cmd.Parameters
  136.                cmd.Parameters.AddWithValue("@dni", dni)
  137.                cmd.Parameters.Add("@msj", SqlDbType.VarChar, 30).Direction = ParameterDirection.Output
  138.                cmd.ExecuteNonQuery()
  139.                msj = cmd.Parameters("@msj").Value
  140.            End With
  141.        Catch ex As Exception : Throw ex
  142.        End Try
  143.        cerrar()
  144.        Return msj
  145.    End Function
  146. 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/

Código
  1. Imports biblioteca
  2. Public Class Form1
  3.    Public p As New biblioteca.Class1
  4.    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  5.        listado()
  6.        RadioButton1.Checked = True
  7.    End Sub
  8.    Sub listado()
  9.        Try
  10.            DataGridView1.DataSource = p.listado()
  11.        Catch ex As Exception : MessageBox.Show(ex.Message)
  12.        End Try
  13.    End Sub
  14.  
  15.    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  16.        Try
  17.            p.dni = TextBox1.Text
  18.            p.ape = TextBox2.Text
  19.            p.n = TextBox3.Text
  20.            If RadioButton1.Checked = True Then
  21.                p.s = "M"
  22.            Else
  23.                p.s = "F"
  24.            End If
  25.            p.fn = DateTimePicker1.Value
  26.            p.edad = TextBox4.Text
  27.            p.sueldo = TextBox5.Text
  28.            MessageBox.Show(p.registrar())
  29.        Catch ex As Exception : MessageBox.Show(ex.Message)
  30.        End Try
  31.        listado()
  32.        limpiar()
  33.    End Sub
  34.    Sub limpiar()
  35.        TextBox1.Clear()
  36.        TextBox2.Clear()
  37.        TextBox3.Clear()
  38.        TextBox4.Clear()
  39.        TextBox1.ReadOnly = False
  40.        TextBox5.Clear()
  41.        DateTimePicker1.Value = Now
  42.        RadioButton1.Checked = True
  43.        TextBox1.Focus()
  44.    End Sub
  45.  
  46.    Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged
  47.        Dim ed As Integer
  48.        ed = Now.Year - DateTimePicker1.Value.Year
  49.        TextBox4.Text = ed
  50.    End Sub
  51.  
  52.    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
  53.        Try
  54.            p.dni = TextBox1.Text
  55.            p.ape = TextBox2.Text
  56.            p.n = TextBox3.Text
  57.            If RadioButton1.Checked = True Then
  58.                p.s = "M"
  59.            Else
  60.                p.s = "F"
  61.            End If
  62.            p.fn = DateTimePicker1.Value
  63.            p.edad = TextBox4.Text
  64.            p.sueldo = TextBox5.Text
  65.            MessageBox.Show(p.modificar())
  66.        Catch ex As Exception : MessageBox.Show(ex.Message)
  67.        End Try
  68.        listado()
  69.        limpiar()
  70.    End Sub
  71.  
  72.    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
  73.        Try
  74.            p.dni = TextBox1.Text    
  75.            MessageBox.Show(p.eliminar())
  76.        Catch ex As Exception : MessageBox.Show(ex.Message)
  77.        End Try
  78.        listado()
  79.        limpiar()
  80.    End Sub
  81.  
  82.    Private Sub DataGridView1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataGridView1.Click
  83.        Try
  84.            Dim fila As Integer = DataGridView1.CurrentRow.Index
  85.            With DataGridView1.Rows(fila)
  86.                TextBox1.Text = .Cells(0).Value.ToString
  87.                TextBox2.Text = .Cells(1).Value.ToString
  88.                TextBox3.Text = .Cells(2).Value.ToString
  89.                If .Cells(3).Value.ToString = "M" Then
  90.                    RadioButton1.Checked = True
  91.                Else
  92.                    RadioButton2.Checked = True
  93.                End If
  94.                DateTimePicker1.Value = .Cells(4).Value.ToString
  95.                TextBox4.Text = .Cells(5).Value.ToString
  96.                TextBox5.Text = .Cells(6).Value.ToString
  97.            End With
  98.            TextBox1.ReadOnly = True
  99.        Catch ex As Exception : MessageBox.Show("fila sin datos")
  100.  
  101.        End Try
  102.    End Sub
  103. End Class
  104.  

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 sirva


Nota del Moderador: Por favor, existe la etiqueta Code, la cual puedes usar sin ningún problema.Gracias.
Páginas: 1 [2]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines