Как мне заставить DataGridView показывать выбранную строку? - PullRequest
64 голосов
/ 09 декабря 2011

Мне нужно заставить DataGridView показать выбранное row.

Короче говоря, у меня есть textbox, который изменяет выбор DGV на основе того, что введено в textbox. Когда это происходит, выбор меняется на соответствующий row.

К сожалению, если выбранный row находится вне поля зрения, я должен вручную прокрутить вниз, чтобы найти выбор. Кто-нибудь знает, как заставить DGV показывать выбранный row?

Спасибо!

Ответы [ 9 ]

113 голосов
/ 09 декабря 2011

Вы можете установить:

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

Вот документация MSDN на это свойство.

45 голосов
/ 21 января 2013

Этот лист прокручивается до выбранной строки, не помещая ее сверху.

dataGridView1.CurrentCell = dataGridView1.Rows[index].Cells[0];
20 голосов
/ 02 февраля 2016

Рассмотрим также этот код (использует предложенный путь от компетентного_технологии):

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;
        }
    }
}
10 голосов
/ 09 декабря 2011

Просто поместите эту строку после выбора строки:

dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.SelectedRows[0].Index;
1 голос
/ 09 февраля 2018

// Это работает, учитывает регистр и находит первое вхождение поиска

    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;
    }
1 голос
/ 23 декабря 2016

Обратите внимание, что настройка FirstDisplayedScrollingRowIndex , когда ваш DataGridView не включен, прокрутит список до нужной строки, но полоса прокрутки не будет отражать ее положение.Самым простым решением является повторное включение и отключение DGV.

dataGridView1.Enabled = true;
dataGridView1.FirstDisplayedScrollingRowIndex = index;
dataGridView1.Enabled = false;
1 голос
/ 26 ноября 2014
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 - выбранная ячейка должна быть видимой

0 голосов
/ 06 сентября 2015

Я сделал следующую функцию поиска, она хорошо работает для прокрутки выбора на дисплее.

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 голосов
/ 27 мая 2015

Делая что-то вроде этого:

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

будет работать, только если виден первый столбец.Если он скрыт, вы получите исключение.Это безопаснее:

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

Это сбросит выбор без прокрутки, если целевая строка уже находится на экране.Он также сохраняет текущий выбор столбца, который может иметь значение в тех случаях, когда вы разрешили встроенное редактирование.

...