2
votes

I've got delete button at the end of each row (second column) of DataGridView. On click I remove row from DataGrid and from the list which is data source of my grid.

enter image description here

private List<multiSet> createdMap = new List<multiSet>();

On button click I can delete element form my DataGridView (named DrawGrid ), but it works only for first click, then I can't delete any element

private void DrawGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex < 0)
            return;

        if (e.ColumnIndex == 1)
        {
                createdMap.RemoveAt(e.RowIndex);
                DrawGrid.DataSource = createdMap.ToList();
        }

    }
1
When debugging, does it enter the DrawGrid_CellContentClick or does just nothing happen when you click the button? - Blake Thingstad
What's the code that creates the rows? - dcg
yes, after ferst delete on debugging it enter DrawGrid_CellContentClick, but nothing more happens - it clames that column index is 0 (although buttons column =1) - eudaimonia
when you first set the DataSource of DrawGrid try doing it like this... DrawGrid.DataSource = new BindingSource() { DataSource = createdMap.ToList() }; and remove DrawGrid.DataSource = createdMap.ToList() in DrawGrid_CellContentClick. - Blake Thingstad
Then to refresh grid, just set DrawGrid.DstaSource = null and then DrawGrid.DataSource = createdMap;. - Reza Aghaei

1 Answers

0
votes

I'm using only 2 columns and form my DataGridView Design MetroUI framework, so I don't need to check if my column index is 1, because it is impossible to click column 0, which is used to edit numbers.

So it's enough to delete my elements just right that:

private void DrawGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex < 0)
            return;

        createdMap.RemoveAt(e.RowIndex);
        DrawGrid.DataSource = createdMap.ToList();
    }

According to @RezaAghaei answer this is better idea:

private void MultisetGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;

            if (e.ColumnIndex == 1)
            {
                createdMap.RemoveAt(e.RowIndex);
                DrawGrid.DataSource = null;
                DrawGrid.DataSource = createdMap;
            }

        }