Remove all rows from datagridview except first

PARTH DESAI 61 Reputation points
2021-04-22T21:57:39.417+00:00

Hello,

I wanted to remove all rows from datagridview in C# windows form application except the first row.
I tried with below code but It removes only few rows not all.

>     public static void ClearDataGridViewRows(DataGridView dataGridView)

>         {

>           foreach (DataGridViewRow row in dataGridView.Rows)

>           {

>             if (dataGridView.Rows.Count == 1) continue;

>             dataGridView.Rows.RemoveAt(dataGridView.Rows.Count - 1);

>           }

>         }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,251 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,036 Reputation points
    2021-04-22T23:15:46.9+00:00

    Hello,

    Use a while statement e.g.

    using System;  
    using System.Windows.Forms;  
      
    namespace DataGridViewCombo1  
    {  
        public partial class Form2 : Form  
        {  
            public Form2()  
            {  
                InitializeComponent();  
            }  
      
            private void Form2_Load(object sender, EventArgs e)  
            {  
                dataGridView1.RowCount = 5;  
      
                for (int index = 0; index < dataGridView1.Rows.Count -1; index++)  
                {  
                    dataGridView1.Rows[index].Cells[0].Value = index;  
                }  
            }  
      
            private void RemoveButton_Click(object sender, EventArgs e)  
            {  
                dataGridView1.AllowUserToAddRows = false;  
      
                try  
                {  
                    while (dataGridView1.Rows.Count > 1)  
                    {  
                        dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);  
                    }  
                }  
                finally  
                {  
                    dataGridView1.AllowUserToAddRows = true;  
                }  
            }  
        }  
    }  
      
    

    ---
    91033-kpmvp.png

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,571 Reputation points
    2021-04-23T06:29:30.65+00:00

    The first row of the dataGridView is the header row.

    Do you want to delete all data rows and keep only this header row?

    If so, you can try the following code:

                var dt = dataGridView1.DataSource as DataTable;  
                dt.Rows.Clear();  
                dataGridView1.DataSource = dt;  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments