DatagridView Select last row

后端 未结 8 2025
你的背包
你的背包 2021-02-14 17:20

I have some trouble with setting the last row in my datagridview selected. I select the last row this way:

if (grid.Rows.Count > 0)
{
    try
    {
        gr         


        
相关标签:
8条回答
  • 2021-02-14 17:31
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;
    
    0 讨论(0)
  • 2021-02-14 17:31

    Eventually the last row is empty because it's the empty row with which the user can add a new row. This row cannot be selected. Have you tried grid.Rows.Count - 2? As an alternative, you can set AllowUserToAddRows to false.

    0 讨论(0)
  • 2021-02-14 17:37

    Your 'catch' block for IndexOutOfRangeException is empty, and will not display any error at all.

    Either your question is not exact, or the exception is being thrown somewhere else.

    EDIT: Having looked through your call stack that you added, I can see that the error is, indeed, not being thrown here, but rather in the CurrencyManager class's Current/Item properties, which is ultimately being triggered by the call to the CurrentCell setter.

    Bottom line: the problem is not in this code; the exception is being thrown by some other piece of code triggered by your setting the current cell.

    0 讨论(0)
  • 2021-02-14 17:43

    Try:

    dataGridView1.ClearSelection();//If you want
    
    int nRowIndex = dataGridView1.Rows.Count - 1;
    int nColumnIndex = 3;
    
    dataGridView1.Rows[nRowIndex].Selected = true;
    dataGridView1.Rows[nRowIndex].Cells[nColumnIndex].Selected = true;
    
    //In case if you want to scroll down as well.
    dataGridView1.FirstDisplayedScrollingRowIndex = nRowIndex;
    

    Gives following output: (Last row, scrolled and selected)

    alt text

    0 讨论(0)
  • 2021-02-14 17:49

    Have you thought about using Linq for this?

        grid.Rows.OfType<DataGridViewRow>().Last().Selected = true;
        grid.CurrentCell = grid.Rows.OfType<DataGridViewRow>().Last().Cells.OfType<DataGridViewCell>().First(); // if first wanted
    
    0 讨论(0)
  • 2021-02-14 17:49

    To avoid the IndexOutOfRangeException make sure only to select a visible row. I suggest:

    // Find last visible row
    DataGridViewRow row = dataGridView1.Rows.Cast<DataGridViewRow>().Where(r => r.Visible).Last(); 
    // scroll to last row if necessary
    dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows.IndexOf(row);
    // select row
    row.Selected = true;
    
    0 讨论(0)
提交回复
热议问题