Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all DataGridView rows on form load?

How can I remove all the datagridview rows except the column headers?

I tried:

dataGridView1.Rows.clear();

but it does not work.

I tried to loop over the rows and use the RemoveAt method, but it does not remove all rows:

private void Form5_Load(object sender, EventArgs e)
{       
    dataGridView1.AutoGenerateColumns = true;
    SqlConnection con = new SqlConnection(@"Data Source=.\myserver;Initial Catalog=test;Integrated Security=True");
    adapter = new SqlDataAdapter("SELECT id as [#], description as [Description], unit as [Unit], amount as [Amount], unitPrice as [Unit Price], total as [Total] FROM tbl_poMaterials", con);
    adapter.SelectCommand.CommandType = CommandType.Text;
    DataTable tb = new DataTable();
    adapter.Fill(tb);
    SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
    dataGridView1.DataSource = tb;

    dataGridView1.Columns[0].Width = 30;
    dataGridView1.Columns[0].ReadOnly = true;
    dataGridView1.Columns[1].Width = 660;

    for (int i = 0; i < tb.Rows.Count; i++)
    {
        tb.Rows.RemoveAt(i);
    }
}
like image 1000
user891757 Avatar asked Jan 08 '12 07:01

user891757


1 Answers

I use

dataGridViewResult.Rows.Clear();

to clear every rows without delete columns.

like image 55
StefanoM5 Avatar answered Nov 08 '22 11:11

StefanoM5