Formulario de Búsqueda

Fecha: 30/Nov/2004 (24 de noviembre 2004)

Autor: José Manuel Makepeace Alconero (makepeace@mailderiver.com.ar)

 

.

En este artículo veremos como crear un formulario sencillo para búsqueda por criterios en una tabla de datos, por medio de una conexión a SQL Server

A continuación, el código del formulario:

Imports System

Imports System.Data

Imports System.Data.SqlClient

Imports System.Windows.Forms

Public Class Form1

    Inherits System.Windows.Forms.Form

    Dim dv As DataView

#Region " Código generado por el Diseñador de Windows Forms "

    Public Sub New()

        MyBase.New()

        'El Diseñador de Windows Forms requiere esta llamada.

        InitializeComponent()

        'Agregar cualquier inicialización después de la llamada a InitializeComponent()

    End Sub

    'Form reemplaza a Dispose para limpiar la lista de componentes.

    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)

        If disposing Then

            If Not (components Is Nothing) Then

                components.Dispose()

            End If

        End If

        MyBase.Dispose(disposing)

    End Sub

 

    'Requerido por el Diseñador de Windows Forms

    Private components As System.ComponentModel.IContainer

 

    'NOTA: el Diseñador de Windows Forms requiere el siguiente procedimiento

    'Puede modificarse utilizando el Diseñador de Windows Forms.

    'No lo modifique con el editor de código.

    Friend WithEvents Label1 As System.Windows.Forms.Label

    Friend WithEvents ComboBox1 As System.Windows.Forms.ComboBox

    Friend WithEvents Label2 As System.Windows.Forms.Label

    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox

    Friend WithEvents DataGrid1 As System.Windows.Forms.DataGrid

    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

        Me.Label1 = New System.Windows.Forms.Label

        Me.ComboBox1 = New System.Windows.Forms.ComboBox

        Me.Label2 = New System.Windows.Forms.Label

        Me.TextBox1 = New System.Windows.Forms.TextBox

        Me.DataGrid1 = New System.Windows.Forms.DataGrid

        CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).BeginInit()

        Me.SuspendLayout()

        '

        'Label1

        '

        Me.Label1.Location = New System.Drawing.Point(8, 8)

        Me.Label1.Name = "Label1"

        Me.Label1.Size = New System.Drawing.Size(144, 16)

        Me.Label1.TabIndex = 0

        Me.Label1.Text = "Buscar en"

        '

        'ComboBox1

        '

        Me.ComboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList

        Me.ComboBox1.Location = New System.Drawing.Point(8, 24)

        Me.ComboBox1.Name = "ComboBox1"

        Me.ComboBox1.Size = New System.Drawing.Size(192, 21)

        Me.ComboBox1.TabIndex = 1

        '

        'Label2

        '

        Me.Label2.Location = New System.Drawing.Point(208, 8)

        Me.Label2.Name = "Label2"

        Me.Label2.Size = New System.Drawing.Size(100, 16)

        Me.Label2.TabIndex = 2

        Me.Label2.Text = "Texto a buscar"

        '

        'TextBox1

        '

        Me.TextBox1.Location = New System.Drawing.Point(208, 24)

        Me.TextBox1.Name = "TextBox1"

        Me.TextBox1.Size = New System.Drawing.Size(264, 20)

        Me.TextBox1.TabIndex = 3

        Me.TextBox1.Text = ""

        '

        'DataGrid1

        '

        Me.DataGrid1.DataMember = ""

        Me.DataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText

        Me.DataGrid1.Location = New System.Drawing.Point(8, 48)

        Me.DataGrid1.Name = "DataGrid1"

        Me.DataGrid1.Size = New System.Drawing.Size(576, 304)

        Me.DataGrid1.TabIndex = 4

        '

        'Form1

        '

        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)

        Me.ClientSize = New System.Drawing.Size(592, 381)

        Me.Controls.Add(Me.DataGrid1)

        Me.Controls.Add(Me.TextBox1)

        Me.Controls.Add(Me.Label2)

        Me.Controls.Add(Me.ComboBox1)

        Me.Controls.Add(Me.Label1)

        Me.Name = "Form1"

        Me.Text = "Form1"

        CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).EndInit()

        Me.ResumeLayout(False)

 

    End Sub

 

#End Region

 

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

        'Parámetros para la consulta

        Dim servidor As String = "SERVER"

        Dim bd As String = "BD"

        Dim usuario As String = "USER"

        Dim password As String = "PASSWORD"

        Dim tabla As String = "nombretabla"

        Dim campos As String = "*"

        Dim orden As String = "campo"

        'Creamos la conexión

        Dim conexion As New SqlConnection("data source=" & servidor & _

            ";initial catalog=" & bd & ";uid=" & usuario & _

            ";password=" & password)

        'Definimos el dataset y el dataadapter

        Dim ds As New DataSet

        Dim da As New SqlDataAdapter("select " & campos & " from " & tabla & _

            IIf(orden.Length > 0, " order by " & orden, ""), conexion)

        'Llenamos al dataset con el resultado de la consulta

        da.Fill(ds)

        'Asignamos la tabla que utiliza el dataview

        dv = ds.Tables(0).DefaultView

        'Asignar las restricciones al dataview

        dv.AllowDelete = False

        dv.AllowEdit = False

        dv.AllowNew = False

        'Enlazamos el datagrid con el dataview

        DataGrid1.DataSource = dv

        'Llenamos el combo con el listado de campos

        Dim c As DataColumn

        For Each c In ds.Tables(0).Columns

            Me.ComboBox1.Items.Add(c.ColumnName)

        Next

        'Asignar el primer elemento como seleccionado

        Me.ComboBox1.SelectedIndex = 0

    End Sub

 

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged

        'Realizar la búsqueda según la columna

        Dim filtro As String

        If dv.Table.Columns(Me.ComboBox1.Text).DataType.Name.ToLower = "string" Then

            filtro = Me.ComboBox1.Text & " like '" & Me.TextBox1.Text & "%'"

        Else

            If Me.TextBox1.Text.Trim.Length > 0 Then

                filtro = Me.ComboBox1.Text & " = " & Me.TextBox1.Text

            End If

        End If

        dv.RowFilter = filtro

    End Sub

 

End Class

El resultado al ejecutar el código, habiendo asignado los parametros de conexion (SERVER,BASE DE DATOS, USER, PASSWORD), y la informacion de la tabla, seria similar al siguiente, obviamente con los campos que tu tabla tiene, seria el siguiente:

 
Solo debemos seleccionar el campo en base al cual buscaremos, y escribir el valor a buscar. Si éste código les es útil, por favor voten por él!

ir al índice