I would like to delete a row from the datagrid when pressing a "Delete" button
I have this:
private void btnEliminar_Click(object sender, EventArgs e)
{
if (Id != "")
{
XXXXX Item = new XXXXX();
using (var context = new PruebaEnti())
{
Item = context.xxxxx.FirstOrDefault(x => x.Id == Id);
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
context.SaveChanges();
}
}
}
I get this error:
Additional information: Rows cannot be deleted programmatically unless the DataGridView is data-bound with an IBindingList that supports change notification and allows deletion.
First you must take into account that in order to see the data in your datagridview you must have a data source linked to it, so you should put in the Load event of your form:
In this way the loaded grid appears.
Now to remove an element you must do this:
In this way you delete the object from the database, now what would come would be to update the datagridview since the information changed, therefore you must reload the data source:
And the updated information will be displayed in the grid