tags:

views:

948

answers:

4

I have a databound DataGridView. When a new row is added and the user presses 'Esc' I want to delete the entire row. How can I do this?

A: 

Hi,

What are you using VB.NET, C#, ASP.NET, 2003, 2005, 2008?

Pace
that should be a comment and not an answer :)
balexandre
Ooops! Your right, sorry :)
Pace
+4  A: 

quite easy actually

private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)27)
    {
        if (dataGridView1.Rows.Count > 0)
        {
            dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);
            MessageBox.Show("Last row deleted!");
        }
        e.Handled = true;
    }
}

but take in mind that:

Rows cannot be programmatically removed unless the DataGridView is data-bound to an IBindingList that supports change notification and allows deletion

balexandre
A: 

Rows cannot be programmatically removed unless the DataGridView is data-bound to an IBindingList that supports change notification and allows deletion.

Plz Give the answer to [email protected]

why do you give your mail?...
eKek0
A: 

If you want to remove rows from the DataGrid, you have to use a BindingSource instead of a list, otherwise you will get an exception when doing it.

try this:

public partial class YourForm : Form {

  private BindingSource _source = new BindingSource();

  public YourForm() {
    List<Model> list = _service.GetList();
    _source.DataSource = list;
    _grid.DataSource = _source;
  }
}

Now you can play around with your datasource and the grid will behave itself. Don't forget to call _grid.Refresh() after each change.

Cheers,

Andre carlucci

andrecarlucci