2011-12-08 23 views
48

Necesito forzar el DataGridView para mostrar el row seleccionado.¿Cómo hago para que DataGridView muestre la fila seleccionada?

En resumen, tengo un textbox que cambia la selección DGV según lo que se tipea en el textbox. Cuando esto sucede, la selección cambia a la coincidencia row.

Desafortunadamente, si el row seleccionado está fuera de la vista, tengo que desplazarme manualmente hacia abajo para encontrar la selección. ¿Alguien sabe cómo forzar el DGV para mostrar el row seleccionado?

Gracias!

+7

Sólo hay que establecer la propiedad currentCell, la DGV se desplazará para que sea visible. –

Respuesta

86

puede ajustar:

dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.SelectedRows[0].Index; 

Aquí es el MSDN documentation en esta propiedad.

+0

¡Gracias! He estado luchando con intentar encontrar mi falla lógica en mi uso de CurrentCell que no funcionaba universalmente. ¡Pero puedo conectar el número de fila que he estado usando todo este tiempo y funciona como un encanto! – clweeks

+0

simple y perfecto (y) –

10

sólo hay que poner esa línea después de la selección de la fila:

dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.SelectedRows[0].Index; 
+1

¡Lo perdí en un minuto! –

32

éste se desplaza a la fila seleccionada sin ponerlo en la parte superior.

dataGridView1.CurrentCell = dataGridView1.Rows[index].Cells[0]; 
+2

Definitivamente más fácil de usar que 'DataGridView.FirstDisplayedScrollingRowIndex', gracias! – Nolonar

+4

A diferencia de FirstDisplayedScrollingRowInde, esto también mueve la flecha de la fila a la fila correcta, selecciona la fila y anula la selección de cualquier otra fila. – Polyfun

1
int rowIndex = -1; 
foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
    if (row.Cells[0].Value.ToString().Equals(searchString)) 
    { 
     rowIndex = row.Index; 
     break; 
    } 
} 
if (rowIndex >= 0) 
{ 
    dataGridView1.CurrentCell = dataGridView1[visibleColumnIndex, rowIndex]; 
} 

visibleColumnIndex - seleccionados célula debe ser visible

0

Hacer algo como esto:

dataGridView1.CurrentCell = dataGridView1.Rows[index].Cells[0];

sólo funcionará si la primera columna es visible. Si está oculto, obtendrá una excepción. Esto es más seguro:

var column = dataGridView1.CurrentCell != null ? dataGridView1.CurrentCell.ColumnIndex : dataGridView1.FirstDisplayedScrollingColumnIndex; dataGridView1.CurrentCell = dataGridView1.Rows[iNextHighlight].Cells[column];

Esto restablecerá la selección sin necesidad de desplazarse si la fila de destino ya está en la pantalla. También conserva la opción de columna actual que puede importar en los casos en que haya permitido la edición en línea.

0

Hice la siguiente función de búsqueda que funciona bien para desplazarse por las selecciones en la pantalla.

private void btnSearch_Click(object sender, EventArgs e) 
{ 
    dataGridView1.ClearSelection(); 
    string strSearch = txtSearch.Text.ToUpper(); 
    int iIndex = -1; 
    int iFirstFoundRow = -1; 
    bool bFound = false; 
    if (strSearch != "") 
    { 
    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 

    /* Select All Rows Starting With The Search string in row.cells[1] = 
    second column. The search string can be 1 letter till a complete line 
    If The dataGridView MultiSelect is set to true this will highlight 
    all found rows. If The dataGridView MultiSelect is set to false only 
    the last found row will be highlighted. Or if you jump out of the 
    foreach loop the first found row will be highlighted.*/ 

    foreach (DataGridViewRow row in dataGridView1.Rows) 
    { 
    if ((row.Cells[1].Value.ToString().ToUpper()).IndexOf(strSearch) == 0) 
    { 
     iIndex = row.Index; 
     if(iFirstFoundRow == -1) // First row index saved in iFirstFoundRow 
     { 
     iFirstFoundRow = iIndex; 
     } 
     dataGridView1.Rows[iIndex].Selected = true; // Found row is selected 
     bFound = true; // This is needed to scroll de found rows in display 
     // break; //uncomment this if you only want the first found row. 
    } 
    } 
    if (bFound == false) 
    { 
    dataGridView1.ClearSelection(); // Nothing found clear all Highlights. 
    } 
    else 
    { 
    // Scroll found rows in display 
    dataGridView1.FirstDisplayedScrollingRowIndex = iFirstFoundRow; 
    } 
} 

}

+0

Este es el que yo uso. – Mac

14

Ten en cuenta también el código (utiliza el de competent_tech manera sugerida):

private static void EnsureVisibleRow(DataGridView view, int rowToShow) 
{ 
    if (rowToShow >= 0 && rowToShow < view.RowCount) 
    { 
     var countVisible = view.DisplayedRowCount(false); 
     var firstVisible = view.FirstDisplayedScrollingRowIndex; 
     if (rowToShow < firstVisible) 
     { 
      view.FirstDisplayedScrollingRowIndex = rowToShow; 
     } 
     else if (rowToShow >= firstVisible + countVisible) 
     { 
      view.FirstDisplayedScrollingRowIndex = rowToShow - countVisible + 1; 
     } 
    } 
} 
+3

Una respuesta muy funcional ... digna de muchos más votos. – ulatekh

+1

Estoy de acuerdo, ¡así que lo he votado! Funciona mejor que cualquiera de las otras soluciones. – JonP

+2

Funciona muy bien: hice rowtoShow opptional y lo configuré en la última fila si la persona que llama no lo configuró. Ahora se desplaza hacia abajo por defecto. Podría agregar otra firma para darle un mejor nombre. – rheitzman

0

Tenga en cuenta que la fijación de FirstDisplayedScrollingRowIndex cuando su DataGridView no está activado, se desplazará la lista para fila deseada, pero la barra de desplazamiento no reflejará su posición. La solución más simple es volver a habilitar y deshabilitar su DGV.

dataGridView1.Enabled = true; 
dataGridView1.FirstDisplayedScrollingRowIndex = index; 
dataGridView1.Enabled = false; 
0

// esto funciona, es sensible a mayúsculas y busca la primera aparición de búsqueda

private bool FindInGrid(string search) 
    { 
     bool results = false; 

     foreach (DataGridViewRow row in dgvData.Rows) 
     { 
      if (row.DataBoundItem != null) 
      { 
       foreach (DataGridViewCell cell in row.Cells) 
       { 
        if (cell.Value.ToString().Contains(search)) 
        { 
         dgvData.CurrentCell = cell; 
         dgvData.FirstDisplayedScrollingRowIndex = cell.RowIndex; 
         results = true; 
         break; 
        } 

        if (results == true) 
         break; 
       } 
       if (results == true) 
        break; 
      } 
     } 

     return results; 
    } 
Cuestiones relacionadas