viernes, 22 de julio de 2011

VISUAL BASIC .Net

CONECTAR A SQL SERVER CON ADO.NET




 
Este ejemplo crea un formulario llamado Conexión para conectarse a una base de datos de SQL Server llamada Northwind, usando autenticación de windows, la progra del formulario se detalla a continuación.

 
Imports System.Data
Imports System.Data.SqlClient
Public Class Conexion
    Dim WithEvents Cn As New SqlConnection


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Cn.ConnectionString = "data source=VISOAL76;initial catalog=Northwind;integrated security=true"
            Cn.Open()
        Catch XcpSQL As SqlException
            MessageBox.Show(XcpSQL.Number)
        Catch Xcp As Exception
            MessageBox.Show("Se ha producido un error")
        End Try

    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Cn.Close()
        Cn.Dispose()
    End Sub

    Private Sub Cn_StateChange(ByVal sender As Object, ByVal e As System.Data.StateChangeEventArgs) Handles Cn.StateChange
        MessageBox.Show("Estado Actual:" & e.CurrentState.ToString)
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim cm As New SqlCommand("Select companyname from customers", Cn)
        Dim rds As SqlDataReader = cm.ExecuteReader
        ListBox1.Items.Clear()
        Do While rds.Read
            ListBox1.Items.Add(rds.GetString(0))
        Loop
        rds.Close()
    End Sub

    Private Sub Conexion_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub
End Class

No hay comentarios:

Publicar un comentario