Delete a line in Datagrid

Asked

Viewed 7,968 times

1

I’m trying to exclude the line on which you have the focus of a datagrid, I have used the following code:

datagrid.Rows.RemoveAt(e.RowIndex);  

Is returning the following message:

Uncommitted new Row cannot be Deleted.

What’s wrong? Can someone help me?

3 answers

1


It is necessary to define the property AllowUserToAddRows of DataGridView for false.

And to avoid an exception OutOfRangeException, check before if the line index is valid.

var indice = e.RowIndex;
if (indice >= 0) {
    var linha = dataGridView1.Rows[indice];
    if (!linha.IsNewRow)
        dataGridView1.Rows.Remove(linha);
}
  • Amigo @Qmechanic73 if I set the Allowusertoaddrows property of Datagridview to false. No rows will appear.. There is another way. I need to always delete the last line of the datagrid.

  • Using the Following Code dataGridView1.AllowUserToAddRows = false;var index = e.RowIndex;if (index >= 0){ dgvCompeticao.Rows.RemoveAt(index);}gave this exception.: Operation cannot be performed in this Event Handler.

  • @Fabríciosimonealanamendes I edited and put another way without having to touch AllowUserToAddRows.

  • your code is still damage errors Operation cannot be performed in this Event Handler.

  • @Fabriciosimonealanamendes Try the following: BeginInvoke(new Action(delegate { dataGridView1.Rows.RemoveAt(e.RowIndex); }));.

  • @Fabriciosimonealanamendes Another thing, the property AllowUserToAddRows should serve this case, when false she eliminates the last blank line, not allowing the user to add Rows. How are you importing the data? I tested it here by entering data dynamically and it seemed to work well.

  • I’m putting the code in the event Cellenter The data is not imported, it is typed, and so I need to limit the line quantity, which will be saved in the bank

  • @Did you get it? See if this one code works for what you intend to do.

Show 3 more comments

0

You can do it like this:

private void btoDeleletarItem_Click(object sender, EventArgs e)
{
datagrid.Rows.RemoveAt(datagrid.CurrentRow.Index);
}

This way you will be deleting from Datagrid only the row that is selected in the table (Grid). Remember that it is good to check the option Selectionmode for Fullrowselect, so that when a row cell is selected by the user or you the entire row is marked.

-1

Try this:

if (dgvItens.CurrentRow != null)
        {
            listaItens.RemoveAt(dgvItens.CurrentRow.Index);
            dgvItens.DataSource = listaItens.ToList();
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.