none
How do I override default behavior of DataGridView automatically selecting first row after deleting a row? RRS feed

  • Question



  • I'm writing a C# .NET WinForms app that uses a List<string> and a DataGridView to navigate through the various string values in the list. When a user clicks on a row in the DataGridview, the item in the List<string> whose index equals the index of the DataGridView's selected row is loaded. If the user clicks on the third row in DataGridView, the selected index is 2. The item at List[2].StringValue is then loaded into a text box.

    As far as navigating through the list via the DataGridView, this works fine. But when deleting a row, the default behavior is for the first row in the DataGridView to become the newly selected row. When I delete any row after the first row in DataGridView , I want the row before the deleted row to become the newly selected row. In other words...

    If DataGridView has 5 rows and I delete the third row, the fourth row becomes the new third row and I want to make it the selected row.

    If I delete the last row, the row before it becomes the last row and I want to make it the selected row.

    Here's the code I use to delete a row and update the DataGridView...

    private void DeleteRow()
    {
         lstStrings.RemoveAt(currentindex);
         if (currentindex >= lstStrings.Count)
             currentindex--;
         UpdateDGVStrings();
    }
    
    private void UpdateDGVStrings()
    {
         DGVStrings.Rows.Clear();
         for (int i = 0; i < lstStrings.Count; i++)
         {
               DGVString.Rows.Add(lstStrings[i].strValue);
         }
         DGVStrings.Rows[currentindex].Selected = true;
         txtString.Text = lstStrings[currentindex].strValue;
    }

    I've tried calling UpdateDGVStrings() in the RowsRemoved, UserDeletedRow and UserDeletingRow event handlers, but the first row still becomes the new selected row. When and where should I call UpdateDGVStrings() so it will select the row I want instead of the first row?
    • Edited by WikiGrrrl Tuesday, January 30, 2018 9:12 PM typo
    Tuesday, January 30, 2018 9:10 PM

Answers

  • Also here is a version using the DEL key.

    using System;
    using System.Globalization;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        /// <summary>
        /// dataGridView1 has one column set in the IDE
        /// </summary>
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                dataGridView1.UserDeletingRow += DataGridView1_UserDeletingRow;
                dataGridView1.KeyDown += DataGridView1_KeyDown;
            }
    
            private void DataGridView1_KeyDown(object sender, KeyEventArgs e)
            {
                var currentRowIndex = dataGridView1.CurrentRow.Index;
                if (e.KeyCode == Keys.Delete)
                {
                    if (!dataGridView1.CurrentRow.IsNewRow)
                    {
                        dataGridView1.Rows.RemoveAt(currentRowIndex);
                    }              
                }
                if (currentRowIndex - 1 != -1)
                {
                    dataGridView1.CurrentCell = dataGridView1.Rows[currentRowIndex - 1].Cells[0];
                }
            }
            private void DataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
            {
                var currentRowIndex = dataGridView1.CurrentRow.Index;
                if (currentRowIndex -1 != -1)
                {
                    dataGridView1.CurrentCell = dataGridView1.Rows[currentRowIndex - 1].Cells[0];
                }           
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                var dayNames = CultureInfo.CurrentCulture.DateTimeFormat.DayNames;
                foreach (var item in dayNames)
                {
                    dataGridView1.Rows.Add(item);
                }
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by WikiGrrrl Wednesday, January 31, 2018 8:40 PM
    Wednesday, January 31, 2018 12:55 AM
    Moderator

All replies

  • You can get the current row index and determine (if there is one) the row prior to the current row via UserDeletingRow event of the DataGridview then from here set the prior row as the selected row..

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, January 30, 2018 9:17 PM
    Moderator
  • Thanks for your reply, Karen. DataGridView's AllowUserToDeleteRows property would have to be set to true for the UserDeletingRows event to execute. I tried that along with calling UpdateDGVStrings() from within UserDeletingRows(), but I get the same results.

    • Edited by WikiGrrrl Wednesday, January 31, 2018 12:20 AM typo
    Wednesday, January 31, 2018 12:19 AM
  • I was thinking along these lines

    using System;
    using System.Globalization;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        /// <summary>
        /// dataGridView1 has one column set in the IDE
        /// </summary>
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                dataGridView1.UserDeletingRow += DataGridView1_UserDeletingRow;
            }
            private void DataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
            {
                var currentRowIndex = dataGridView1.CurrentRow.Index;
                if (currentRowIndex -1 != -1)
                {
                    dataGridView1.CurrentCell = dataGridView1.Rows[currentRowIndex - 1].Cells[0];
                }           
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                var dayNames = CultureInfo.CurrentCulture.DateTimeFormat.DayNames;
                foreach (var item in dayNames)
                {
                    dataGridView1.Rows.Add(item);
                }
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, January 31, 2018 12:47 AM
    Moderator
  • Also here is a version using the DEL key.

    using System;
    using System.Globalization;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        /// <summary>
        /// dataGridView1 has one column set in the IDE
        /// </summary>
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                dataGridView1.UserDeletingRow += DataGridView1_UserDeletingRow;
                dataGridView1.KeyDown += DataGridView1_KeyDown;
            }
    
            private void DataGridView1_KeyDown(object sender, KeyEventArgs e)
            {
                var currentRowIndex = dataGridView1.CurrentRow.Index;
                if (e.KeyCode == Keys.Delete)
                {
                    if (!dataGridView1.CurrentRow.IsNewRow)
                    {
                        dataGridView1.Rows.RemoveAt(currentRowIndex);
                    }              
                }
                if (currentRowIndex - 1 != -1)
                {
                    dataGridView1.CurrentCell = dataGridView1.Rows[currentRowIndex - 1].Cells[0];
                }
            }
            private void DataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
            {
                var currentRowIndex = dataGridView1.CurrentRow.Index;
                if (currentRowIndex -1 != -1)
                {
                    dataGridView1.CurrentCell = dataGridView1.Rows[currentRowIndex - 1].Cells[0];
                }           
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                var dayNames = CultureInfo.CurrentCulture.DateTimeFormat.DayNames;
                foreach (var item in dayNames)
                {
                    dataGridView1.Rows.Add(item);
                }
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by WikiGrrrl Wednesday, January 31, 2018 8:40 PM
    Wednesday, January 31, 2018 12:55 AM
    Moderator
  • Thanks, Karen! They both work!
    Wednesday, January 31, 2018 8:40 PM
  • Thanks, Karen! They both work!
    Excellent :-)

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, January 31, 2018 10:34 PM
    Moderator