Ahmad Karimi
Ahmad Karimi

Reputation: 27

Get the deleted row's index in a DataGridView

I deleted a row in my DataGridView by selecting it and pressing Delete and would like to get the row's index. How could i do that?

Upvotes: 1

Views: 5517

Answers (4)

Lucien ASSAILLIT
Lucien ASSAILLIT

Reputation: 1

Maybe this will help you.

private void EvtBindingNavigatorDeleteItemClick(object sender, System.EventArgs e)
{
   ToolStripButton MyToolStripButton = (ToolStripButton)sender;
   CustomBindingNavigator MyCustomBindingNavigator = 
   (CustomBindingNavigator)MyToolStripButton.GetCurrentParent();
   CustomDataGridView MyDataGridView = GetDataGridView(MyCustomBindingNavigator);
   int RowIndexDelete = -1;
   BindingSource MyBindingSource = MyCustomBindingNavigator.BindingSource;
   DataTable MyDataTable = (DataTable)MyBindingSource.DataSource;
   foreach ( DataRow MyDataRow in MyDataTable.Rows)
   {
    if (MyDataRow.RowState == DataRowState.Deleted)
        RowIndexDelete = MyDataTable.Rows.IndexOf(MyDataRow);
   }
}

Upvotes: -1

Ahmed
Ahmed

Reputation: 141

Most of the answers in StackOverflow mentioned UserDeletedRow as an event to handle and get the user deleted row index. this event only fired after deleting that row. The correct one must be UserDeletingRow, where by this event you can do something before you lose the deleted row. Now how to get the row index? the answer by using the below code

private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
    {
        int tmp = e.Row.Index;
    }

Upvotes: 1

Alexandru Dicu
Alexandru Dicu

Reputation: 1225

You can get the selected index of the current selected item:

int index = DataGrid1.SelectedIndex;

You can do this before deleting the item and you will know the index.

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94645

You may obtain an index before you delete a row by handling UserDeletingRow event.

 dataGridView1.UserDeletingRow += (sa, ea) =>
  {
    MessageBox.Show(ea.Row.Index.ToString())
  };

Upvotes: 4

Related Questions