Sukanya
Sukanya

Reputation: 1061

How to delete the row from datagridview?

Friends, I'm using datagridview in my windows C# application. We know that When the form with datagridview is loaded a default row is created in the grid. If we type anything in any cell(I've total 6 columns, 2 hidden columns), a new row is created. But if we delete the entry the newly created row is not deleted. In this way we can create as many row we want without keeping any value inside any cell. I want the datagridview to maximum create 2 such rows and when in both the rows, no value is present, the last row to be deleted (so that grid will have 1 row without any data in it). I've tried to remove row in datagridview1_CellValueChanged event, but it's not working. Which event should I use and how can I get the desired functionality? Please help.

Upvotes: 1

Views: 13035

Answers (4)

A default row is automatically added to allow for user input. If you don't want this, set the DataGridView AllowUserToAddRows property to false.

dataGridView.AllowUserToAddRows = false;

Making it effectively a read-only grid.

Upvotes: 0

Israel Margulies
Israel Margulies

Reputation: 8952

If you loop using the same grid RowCount it won't work

  for(int i = 0;i<dataGridMaster.Rows.Count;i++)
            {
               dataGridMaster.Rows.RemoveAt(i);
            }

It Will not do the job correctly because the Count of rows changes while looping.

Instead assign the number to a local variable like:

Int loopNum = dataGridMaster.Rows.Count;
for(int i = 0;i<loopNum ;i++)
            {
               dataGridMaster.Rows.RemoveAt(i);
            }

Upvotes: 0

Kishore Kumar
Kishore Kumar

Reputation: 12864

We have two function to remove rows from DataGridView

dataGridView1.Rows.Remove();
dataGridView1.Rows.RemoveAt();

you can provide the index of the row as parameter to remove the row.

You can give in Validating or Validated event of DataGridView

Upvotes: 1

Vinod
Vinod

Reputation: 4872

Try this:

DataGridView1.Rows.Remove(row);

Upvotes: 1

Related Questions