DataGridView - Фокус определенной ячейки - PullRequest
39 голосов
/ 07 февраля 2011

Как установить фокус на любую указанную ячейку в DataGridView?Я ожидал простого способа, такого как Focus (rowindex, columnindex), но это не так просто.

Ответы [ 10 ]

77 голосов
/ 07 февраля 2011

Установите текущую ячейку как:

DataGridView1.CurrentCell = DataGridView1.Rows[rowindex].Cells[columnindex]

или

DataGridView1.CurrentCell = DataGridView1.Item("ColumnName", 5)

и вы можете напрямую сфокусироваться с помощью редактирования:

dataGridView1.BeginEdit(true)
11 голосов
/ 07 февраля 2011

Вы можете установить Focus для определенного Cell, установив для свойства Selected значение true

dataGridView1.Rows[rowindex].Cells[columnindex].Selected = true;

, чтобы избежать множественного выбора, просто установите

dataGridView1.MultiSelect = false;
7 голосов
/ 07 февраля 2011

проблема с datagridview заключается в том, что он выбирает первую строку автоматически, поэтому вы хотите очистить выбор по

grvPackingList.ClearSelection();
dataGridView1.Rows[rowindex].Cells[columnindex].Selected = true;  

иначе не будет работать

3 голосов
/ 26 мая 2014

У меня была похожая проблема. Я спрятал несколько столбцов, а потом попытался выбрать первый ряд. Это не сработало:

datagridview1.Rows[0].Selected = true;

Поэтому я попытался выбрать cell[0,0], но это также не сработало, потому что эта ячейка не отображалась. Теперь мое окончательное решение работает очень хорошо:

datagridview1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;    
datagridview1.CurrentCell = datagridview1.FirstDisplayedCell;

Таким образом, выбирается полный первый ряд.

1 голос
/ 09 февраля 2015
public void M(){ 
  dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
  dataGridView1.CurrentCell.Selected = true; 
  dataGridView1.BeginEdit(true);
}
0 голосов
/ 16 марта 2018
            //For me it's the best way to look for the value of a spezific column
            int seekValue = 5;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                var columnValue = Convert.ToInt32(row.Cells["ColumnName"].Value);
                if (columnValue == seekValue)
                {
                    dataGridView1.CurrentCell = row.Cells[0];
                }
            }
0 голосов
/ 28 ноября 2016

Просто вставьте и передайте Gridcolor () в любом месте, где вы хотите.

Private Sub Gridcolor()
    With Me.GridListAll
        .SelectionMode = DataGridViewSelectionMode.FullRowSelect
        .MultiSelect = False
        '.DefaultCellStyle.SelectionBackColor = Color.MediumOrchid
    End With
End Sub
0 голосов
/ 30 декабря 2015

в событии form_load (отправитель объекта, EventArgs e) попробуйте это

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

этот код делает акцент на последнем ряду и первой ячейке

0 голосов
/ 18 февраля 2014

DataGridView1.CurrentCell = DataGridView1.Item ("ColumnName", 5)

0 голосов
/ 05 сентября 2013
 private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        int row = e.RowIndex;
        int col = e.ColumnIndex;
        if (row < 0 || col != 3)
            return;
        if (e.FormattedValue.ToString().Equals(String.Empty))
        {
        }

        else
        {
            double quantity = 0;
            try
            {
                quantity = Convert.ToDouble(e.FormattedValue.ToString());
                if (quantity == 0)
                {
                    MessageBox.Show("The quantity can not be Zero", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    e.Cancel = true;
                    return;
                }
            }
            catch
            {
                MessageBox.Show("The quantity should be decimal value.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Cancel = true;
                return;
            }
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...