Buscar registro en un datagridview

Amigos que tal buenas tardes quisiera ver si me pueden ayudar a buscar y seleccionar un dato en la columna(1) de un datagridview el cual lo voy escribiendo en un textbox tengo este código funciona bien solo que busca en todas las columnas.

For Each row As DataGridViewRow In dgvClientes.Rows
If row.IsNewRow Then Exit For
For Each cell As DataGridViewCell In row.Cells()
If cell.GetType IsNot GetType(DataGridViewTextBoxCell) Then Continue For
If cell.Value.ToString.ToUpper.Contains(TextBox9.Text) Then
dgvClientes.CurrentCell = cell
Exit Sub
End If
Next
Next

De ante mano agradezco a todos que de una y otra forma ayudan a los que carecemos de conocimientos con comentarios positivos en pro del aprendizaje.

1 respuesta

Respuesta
1

adapta el siguiente código...

txtBusqueda = contol TextBox para buscar

dgvDatos = control DataGridView en donde deseas buscar

ComboBoxColumnas = control ComboBox que contiene los nombres de las columnas

Function BuscarTexto(Texto As String, Busqueda As String) As Boolean
        Dim i As Integer
        i = InStr(1, Texto, Busqueda)
        If i > 0 Then
            BuscarTexto = True
        Else
            BuscarTexto = False
        End If
    End Function
    Private Sub txtBusqueda_TextChanged(sender As Object, e As EventArgs) Handles txtBusqueda.TextChanged
        Try
            If txtBusqueda.Text = Nothing Then
                For y As Integer = 0 To dgvDatos.RowCount - 1
                    dgvDatos.Rows(y).DefaultCellStyle.BackColor = Color.White
                    dgvDatos.CurrentCell = dgvDatos.Rows(0).Cells(0)
                Next
                Exit Sub
            End If
            Dim i As Integer
            For i = 0 To Me.dgvDatos.RowCount - 1
                If BuscarTexto(Me.dgvDatos.Rows(i).Cells(ComboBoxColumnas.Text).Value.ToString, Me.txtBusqueda.Text.Trim)=true Then
                    dgvDatos.Rows(i).DefaultCellStyle.BackColor = Color.Yellow
                End If
            Next
        Catch ex As Exception
        End Try
        Try
            Dim x As Integer
            For x = 0 To Me.dgvDatos.RowCount - 1
                If BuscarTexto(Me.dgvDatos.Rows(x).Cells(ComboBoxColumnas.Text).Value.ToString, Me.txtBusqueda.Text.Trim) = False Then
                    dgvDatos.Rows(x).DefaultCellStyle.BackColor = Color.White
                End If
            Next
        Catch ex As Exception
        End Try
        Dim iFila As Integer
        For z As Integer = 0 To dgvDatos.RowCount - 1
            If dgvDatos.Rows(z).DefaultCellStyle.BackColor = Color.Yellow = True Then
                iFila = dgvDatos.Rows(z).Index
                dgvDatos.Rows(iFila).Selected = True
                dgvDatos.CurrentCell = dgvDatos.Rows(iFila).Cells(0)
            End If
        Next
    End Sub

¡Gracias! Estimado mickehuertas es muy bueno tu ejemplo, solo una interrogante si no fuera mucha molestia como hacer para que en vez que la selección siempre se vaya al ultimo dato con coincidencia se quede en elprimero. Otra vez más muchísimas gracias

Prueba colocándole en la última parte un "Exit Sub"...

      For z As Integer = 0 To dgvDatos.RowCount - 1
            If dgvDatos.Rows(z).DefaultCellStyle.BackColor = Color.Yellow = True Then
                iFila = dgvDatos.Rows(z).Index
                dgvDatos.Rows(iFila).Selected = True
                dgvDatos.CurrentCell = dgvDatos.Rows(iFila).Cells(0)
                Exit sub 'AQUÍ
            End If
        Next

Coméntame si te funcionó la última parte...

¡Gracias! Una vez más estimado mickehuertas funciono colocando exit sub. Pero hay otro inconveniente como lo muestro en la imagen adjunta y es que cuando escribo una C, la selección debería de posicionarse en consorcio ya que es la única que empieza con C pero no se intentar ahí incluso si escribo CO tampoco, y es que al parecer encuentra coincidencia en "CONTRATISTAS", alguna forma de que busque por el contenido de la celda pero solo por las letras iniciales y no las que estén al centro. Gracias

Cierto, nuevamente cambia la última parte:

 Dim iFila As Integer
        For z As Integer = 0 To dgvDatos.RowCount - 1
            If dgvDatos.Rows(z).DefaultCellStyle.BackColor = Color.Yellow = True Then
                If dgvDatos.Rows(z).Cells(ComboBoxColumnas.Text).Value.ToString.StartsWith(txtBusqueda.Text.Trim) Then
                    iFila = dgvDatos.Rows(z).Index
                    dgvDatos.Rows(iFila).Selected = True
                    dgvDatos.CurrentCell = dgvDatos.Rows(iFila).Cells(0)
                    Exit Sub
                End If
            End If
        Next

Avísame...

Si funciona estimado amigo, una vez muchas gracias, pero solo para terminar porque me pinta los demás registros si esos no empiezan con C. Gracias.

Así es, pinta de amarillo todas las columnas que "contengan" la cadena que estás escribiendo. Para cambiar solamente a los que "empiezan" con tu cadena, cambia la segunda parte ( For i = 0 To Me. DgvDatos. RowCount - 1...; que es donde pinta las filas). Colócale una condición algo así:

Dim i As Integer
For i = 0 To Me.dgvDatos.RowCount - 1
       If BuscarTexto(Me.dgvDatos.Rows(i).Cells(ComboBoxColumnas.Text).Value.ToString, Me.txtBusqueda.Text.Trim)=true Then
           If dgvDatod.Rows(i).Cells(ComboBoxColumna.Text).Value.ToString.StartsWith(txtBusqueda.Text.Trim) Then
              dgvDatos.Rows(i).DefaultCellStyle.BackColor = Color.Yellow
           End If
       End If
Next

En la parte anterior es "pinta de amarillo todas las filas" no "pinta de amarillo todas las columnas"...

¡Gracias! Estimado amigo mickehuertas quedo sensacional te lo agradezco de todo corazón. Te deseo muchos éxitos y bendiciones en tu vida profesional y personal.

Nota: Si por ahí encuentro otro vacío te lo hago saber

Gracias una vez más

Un gusto... Cuenta conmigo por cualquier otra cosa...

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas