0
votes

I'm trying to implement DeleteItem functionality on my DataGridView. I have the following event:

private void btnDeleteDjelatnik_Click(object sender, EventArgs e)
{
    int idDjelatnik = -1;
    int index = djelatnikDataGrid.CurrentRow.Index;
    Int32.TryParse(djelatnikDataGrid.Rows[index].Cells[0].Value.ToString(), out idDjelatnik);
    r.DeleteDjelatnik(idDjelatnik);
}

I'm trying to get selected rows ID Column so I can pass it to my Delete method: DeleteDjelatnik(int slectedID);

the following line always gives me value of 3:

int index = djelatnikDataGrid.CurrentRow.Index;

I also tried

int index = djelatnikDataGrid.SelectedRows[0].Index; 

but I'm getting ArgumentOutOfRange exception, yes my SelectionMode is on FullRowSelect

How to get this to work?

3
try datagridview.CurrentCell.RowIndexStack Overflow
The CurrentRow and SelectedRow may not be same. CurrentRow will returns a row that cell is active. The SelectedRows returns the selection, so you should be using djelatnikDataGrid.SelectedRows[0].Hari Prasad
I already tried datagridview.CurrentCell.RowIndex and I still get value 3 no matter what row I pick :/solujic
as I said int index = djelatnikDataGrid.SelectedRows[0].Index; throws ArgumentOutOfRange exceptionsolujic
That clearly indicates you don't have any rows selected.Hari Prasad

3 Answers

1
votes

Use DataGridView's UserDeletingRow event,

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

Hope helps,

0
votes

Since DataGridView Index property doesn't return correct value I wrote this piece of code:

public int djelatnikSelectedRowIndex { get; set; }

private void djelatnikDataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
    djelatnikSelectedRowIndex = e.RowIndex;
}
0
votes

The real problem was DeleteItem property in my BindingNavigator!

Before I set it to "None" it would delete the row from my DataGridView before the execution of "btnDeleteDjelatnik_Click" and mess up the indexation so I couldn't get the real ID of the row I wanted to delete!

My method now looks like this:

private void btnDeleteDjelatnik_Click(object sender, EventArgs e)
{
    int index = djelatnikDataGrid.SelectedRows[0].Index;
    int idDjelatnik = -1;
    Int32.TryParse(djelatnikDataGrid["IDDjelatnik", index].Value.ToString(), out idDjelatnik);
    r.DeleteDjelatnik(idDjelatnik);
    djelatnikDataGrid.Rows.RemoveAt(index);
}

Thanks for help everyone!