简体   繁体   中英

Removing the first row in DataGridView actually removes all rows

I'm creating an application in C#, Windows Forms.

I have a DataGridView and in it I have a column which contains Button s ( DataGridView Button columns). I created an On Button click event and so it calls a method which removes a row:

private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e) 
{
    try
    {
        if (e.ColumnIndex == 5)
        {
            if (!dataGridView.Rows[e.RowIndex].IsNewRow)
            {
                dataGridView.Rows.Remove(dataGridView.CurrentRow); // removes current row
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: " + ex.Message);
    }
}

I'm first adding rows and then I remove them if I need, if I remove the last row there is no problem. The problem occurs if I try to remove the first or any other row except the last. If - for example - I remove the first row, all rows are deleted. When I debugged it, it seems that the method repeats itself as many times there are rows are in my DataGrid .

Does anyone know how can I solve this problem?

Do you have some other code which selects/sets the current selected row in the DataGridView .

Might be a chance that there is some other code, which is actually sending the space key to the currently selected row, so when a row is deleted, CellClick event also gets fired on the next row. Just a guess BTW.

Also, try to use the CellContentClick or CellMouseClick events.

change: dataGridView.Rows.Remove(dataGridView.CurrentRow); to: dataGridView.Rows.RemoveAt(e.RowIndex);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM