9

I have a DataGridView and a Button. If rows are selected I want to delete them by clicking the button. I tried a couple of commands like RemoveAt, SelectedRows etc., but nothing did work. How can I solve that?

I tried something like:

if (dataGridView2.SelectedRows.Count > 0)
{
    DataGridViewSelectedRowCollection rows = dataGridView2.SelectedRows;
    dataGridView2.Rows.RemoveAt(rows);
} 

but the RemoveAt method does only accept integers. Before I tried it with Selected Cells but then he delets all rows because there is always a cell selected.

4
  • Yes - that is what I mean. Sorry for that Commented Feb 19, 2015 at 9:30
  • 1
    Please show what you have tried even if it didn't work. Then we know the problem and can help to fix it. Commented Feb 19, 2015 at 9:30
  • Note that if you have populated the grid using a datasource, you might want to update that source and grid will automatically update Commented Feb 19, 2015 at 9:34
  • These links might help you. [1]: stackoverflow.com/questions/17976348/… [2]: stackoverflow.com/questions/21038006/… Commented Feb 19, 2015 at 9:35

7 Answers 7

20

If you just want to remove the selected rows from the DataGridView this should do it:

foreach (DataGridViewRow row in yourDataGridView.SelectedRows)
{
    yourDataGridView.Rows.RemoveAt(row.Index);
}

Your code didn't work because you've used RemoveAt(rows) but RemoveAt accepts only the index of the row which you want to remove. You are passing a DataGridViewSelectedRowCollection to it. You can get the index of a row via DataGridViewRow.Index as shown above.

Sign up to request clarification or add additional context in comments.

4 Comments

You may want to add a remark why this works without thowing an 'can't modify the iterated collection'..
@TaW: I guess that SelectedRows creates a new, separate collection that can modify DataGridView.Rows during enumeration because it is not linked with it. Edit Confirmed: referencesource.microsoft.com/#System.Windows.Forms/winforms/…
Interesting. Thanks for digging that up. ListView does the same. OTOH, it looks to me, as if ListBox does the same as well but won't let you enumerate the collection and modify it..
@TaW: but you could use the ListView.SelectedIndices-collection, couldn't you?
2

if you are using a list of model, following code could help:

foreach (DataGridViewRow row in dataGridViewX.SelectedRows)
{
    var val = (int)row.Cells[0].Value;
    Products.Remove(Products.Find(d => d.ProductId == val));
}
dataGridViewX.DataSource = null;
dataGridViewX.DataSource = Products;

Comments

1

you can programmatically find what row you are trying to select:

dataGridViewX.Rows[0].Selected = true;

then delete the selected row:

dataGridViewX.Rows.RemoveAt(dataGridViewX.SelectedRows[0].Index);

Comments

1

You can use something like below

foreach(DataGridViewRow row in dgv1.SelectedRows)
{
    dgv1.Rows.Remove(row);
}

Comments

0

Please Try this, hope it's help

1. To enable delete , set the AutoGenerateDeleteButton to true and specify the delete command in the SqlDataSource.

 DeleteCommand="DELETE From [stores] WHERE [stor_id] = @stor_id"

2. Here we are trying to display a confirmation message before deleting the specified row. In order to doing this we have to write a small Javascript code for display confirmation message.

 function isDelete()
  {
    return confirm("Do you want to delete this row ?");
  }

3. We have to call this Javascript function on OnClientClick event of the delete LinkButton.

<asp:LinkButton ID="DeleteBtn" runat="server" CommandName="Delete"
OnClientClick="return isDelete();">Delete</asp:LinkButton>

4. The follwoing ASP.NET program shows how to delete a row from Gridview and display a confirmation message before deleting the specified row.

Default.aspx /// page

![<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
        function isDelete()
        {
            return confirm("Do you want to delete this row ?");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
    AllowSorting="True" DataSourceID="SqlDataSource1" AllowPaging="True" DataKeyNames="stor_id" >
        <Columns>
        <asp:BoundField ReadOnly="True" HeaderText="stor_id"
        DataField="stor_id" SortExpression="stor_id"></asp:BoundField>
        <asp:BoundField HeaderText="stor_name" DataField="stor_name"
        SortExpression="stor_name"></asp:BoundField>
        <asp:BoundField HeaderText="stor_address" DataField="stor_address"
        SortExpression="stor_address"></asp:BoundField>
        <asp:BoundField HeaderText="city" DataField="city"
        SortExpression="city"></asp:BoundField>
        <asp:BoundField HeaderText="state" DataField="state"
        SortExpression="state"></asp:BoundField>
        <asp:BoundField HeaderText="zip" DataField="zip"
        SortExpression="zip"></asp:BoundField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="DeleteBtn" runat="server" CommandName="Delete"
                OnClientClick="return isDelete();">Delete
                </asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>"
    SelectCommand="select * from stores"
    DeleteCommand="DELETE From \[stores\] WHERE \[stor_id\] = @stor_id" >
    <DeleteParameters>
        <asp:Parameter Name="stor_id" Type="String" />
    </DeleteParameters>
    </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>]

Here is the picture

Check this picture it's might help you

1 Comment

this is a winforms question, not webforms
0

i cam across this , and did not find the correct answer , when you delete a row , if this row is the first in collection , all other rows indices will be changed , and you may delete other rows.so you have to loop till the selecteditems count is equal to zero. or you may miss other selected rows.

Here is my method:

while (dataGridView1.SelectedRows.Count > 0)
    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);

1 Comment

For loop should be used instead of while for (int i = 0; i < dataGridView1.Rows.Count;i++ )
0

You are almost there - try the following code-snippet

if (dataGridView1.SelectedRows.Count > 0) {
    DataGridViewSelectedRowCollection row = dataGridView1.SelectedRows;
    // taking the index of the selected rows and removing/
    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
}
else {  //optional    
    MessageBox.Show("Please select a row");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.