You are on page 1of 7

Buscar un registro o fila en una grilla de tipo DataGridView

Simple cdigo de ejemplo que usa el mtodo Find del componente BindingSource para
buscar un registro en un campo especfico en una tabla

formulario

Controles

Un control DataGridView llamado DataGridView1

Un control Button llamado Button1 ( botn para buscar )

Un control textBox llamado textBox1 ( para ingresar el dato )

Indicar el campo por el cual buscar ( Primer parmetro del mtodo


Find)

Establecer la cadena de conexin a utilizar

Cdigo fuente
Texto planoCopiar cdigo fuenteImprimir
1. Option Explicit On

2. Option Strict On
3.
4. Imports System.Data
5. Imports System.Data.SqlClient
6.
7. Public Class Form1
8.
9.

' ConnectionString para SQL server EXPRESS

10.

Private Const cs As String = "Data Source=(local)\SQLEXPRESS;"


& _

11.

"Integrated Security=True;" & _

12.

"Initial Catalog=la_base_de_datos"

13.
14.
15.

'Declarar un BindingSource
Private BindingSource1 As Windows.Forms.BindingSource = New Bin
dingSource

16.
17.
18.
19.

20.
21.

Private Sub Form1_FormClosed( _


ByVal sender As Object, _
ByVal e As System.Windows.Forms.FormClosedEventArgs) Handle
s Me.FormClosed
BindingSource1.Dispose()
End Sub

22.
23.

Private Sub Form1_Load( _

24.

ByVal sender As System.Object, _

25.

ByVal e As System.EventArgs) Handles MyBase.Load

26.

27.
28.

Button1.Text = "Buscar fila"

29.
30.

Try

31.

' Declarar la conexin y abrir

32.

Using cn As SqlConnection = New SqlConnection(cs)

33.

cn.Open()

34.
35.

' Crear un DataAdapter y pasarle el comando para tr


aer los registros

36.

Dim da As New SqlDataAdapter("SELECT * FROM la_tabl


a", cn)

37.

' DataTable

38.

Dim dt As New DataTable

39.
40.

' llenar el DataTable

41.

da.Fill(dt)

42.
43.

' enlazar el DataTable al BindingSource

44.

BindingSource1.DataSource = dt

45.
46.

' propiedades para el DataGridview

47.

'''''''''''''''''''''''''''''''''''''''

48.

With DataGridView1

49.

' opcional: Sin seleccin mltiple

50.

.MultiSelect = False

51.

' seleccioanr fila completa al hacer clic en un


registro

52.

.SelectionMode = DataGridViewSelectionMode.Full
RowSelect

53.
54.

' enlazar los controles

55.

.DataSource = BindingSource1.DataSource

56.

End With

57.
58.
59.

End Using

60.

' errores

61.

Catch ex As Exception

62.
63.
64.

MsgBox(ex.Message.ToString)
End Try
End Sub

65.
66.

' Funcin que retorna el ndice de la fila

67.

'' ''''''''''''''''''''''''''''''''''''''''''''''''''''

68.

Function Buscar( _

69.

ByVal Columna As String, _

70.

ByVal texto As String, _

71.

ByVal BindingSource As BindingSource) As Integer

72.
73.

Try

74.

' si est vacio salir y no retornar nada

75.

If BindingSource1.DataSource Is Nothing Then

76.
77.

Return -1
End If

78.
79.

' Ejecutar el mtodo Find pasndole los datos

80.

Dim fila As Integer = BindingSource.Find(Columna.Trim,


texto)

81.
82.

' Mover el cursor a la fila obtenida

83.

BindingSource.Position = fila

84.
85.

' retornar el valor

86.

Return fila

87.
88.
89.
90.

' errores
Catch ex As Exception
MsgBox(ex.Message.ToString, MsgBoxStyle.Critical)

91.

End Try

92.

' no retornar nada

93.

Return -1

94.
95.

End Function

96.
97.

' Botn para buscar en el DataGridView

98.

Private Sub Button1_Click( _

99.
100.

ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles Button1.Click

101.
102.

' Pasar el nombre del campo por el cual buscar ,

103.

' el dato, y el BindingSource enlazado al DataGridView

104.
''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''
105.

Dim ret As Integer = Buscar( _

106.

"Nombre", _

107.

TextBox1.Text.Trim, _

108.

BindingSource1)

109.
110.

' si no se encontr ....

111.

If ret = -1 Then

112.

' mostrar un mensaje

113.
cal)

MsgBox("No se encontr la fila", MsgBoxStyle.Criti

114.

Else

115.

With DataGridView1

116.

' volver a enlazar

117.

.DataSource = BindingSource1

118.
' Pasarle el ndice para Visualizar la fila al
comienzo de la grilla
119.

.FirstDisplayedScrollingRowIndex = ret

120.

End With
End If
End Sub

End Class

You might also like