busqueda en una grilla de tipo datagridview
DESCRIPTION
La Búsqueda de registro o dato en una grilla de tipo datagridviewTRANSCRIPT
Buscar un registro o fila en una grilla de tipo DataGridView
Simple código de ejemplo que usa el método Find del componente BindingSource para buscar un registro en un campo específico en una tabla
formulario
Controles
Un control DataGridView llamado DataGridView1 Un control Button llamado Button1 ( botón para buscar ) Un control textBox llamado textBox1 ( para ingresar el dato ) Indicar el campo por el cual buscar ( Primer parámetro del método
Find) Establecer la cadena de conexión a utilizar
Código fuente
Texto plano Copiar código fuente Imprimir
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. 'Declarar un BindingSource 15. Private BindingSource1 As Windows.Forms.BindingSource = New Bin
dingSource 16. 17. Private Sub Form1_FormClosed( _ 18. ByVal sender As Object, _ 19. ByVal e As System.Windows.Forms.FormClosedEventArgs) Handle
s Me.FormClosed 20. BindingSource1.Dispose() 21. 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 conexión 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 selección múltiple 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. MsgBox(ex.Message.ToString)
63. End Try 64. End Sub 65. 66. ' Función 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. Return -1 77. End If 78. 79. ' Ejecutar el método Find pasándole 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. ' errores 89. Catch ex As Exception 90. MsgBox(ex.Message.ToString, MsgBoxStyle.Critical) 91. End Try 92. ' no retornar nada 93. Return -1 94. 95. End Function 96. 97. ' Botón para buscar en el DataGridView 98. Private Sub Button1_Click( _ 99. ByVal sender As System.Object, _ 100. 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. MsgBox("No se encontró la fila", MsgBoxStyle.Criti
cal) 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
Option Explicit OnOption Strict On
Imports System.DataImports System.Data.SqlClient
Public Class Form1
' ConnectionString para SQL server EXPRESS Private Const cs As String = "Data Source=(local)\SQLEXPRESS;" & _