DataGridView行索引始终返回相同的值

时间:2016-08-29 08:34:54

标签: c# winforms datagridview

我试图在DataGridView上实现DeleteItem功能。 我有以下事件:

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);
}

我试图获取选定的行ID列,以便将其传递给我的Delete方法:DeleteDjelatnik(int slectedID);

以下行总是给我3的值:

int index = djelatnikDataGrid.CurrentRow.Index;

我也试过

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

但是我收到了ArgumentOutOfRange异常,是的,我的SelectionMode在FullRowSelect上

如何让它发挥作用?

3 个答案:

答案 0 :(得分:1)

使用DataGridView的UserDeletingRow事件,

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

希望有所帮助,

答案 1 :(得分:0)

由于DataGridView Index属性没有返回正确的值,我编写了这段代码:

public int djelatnikSelectedRowIndex { get; set; }

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

答案 2 :(得分:0)

真正的问题是我的BindingNavigator中的DeleteItem属性!

在我将它设置为“None”之前,它会在执行“btnDeleteDjelatnik_Click”之前从我的DataGridView中删除该行并弄乱索引,因此我无法获取我想要删除的行的真实ID!

我的方法现在看起来像这样:

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);
        }

感谢大家的帮助!