简体   繁体   中英

Deleting multiple rows from my DataGridView leaves 1 behind

List<DataGridViewRow> rowsToDelete = new List<DataGridViewRow>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    DataGridViewCheckBoxCell chk = row.Cells[0] as DataGridViewCheckBoxCell;
    if (Convert.ToBoolean(chk.Value) == true)
        rowsToDelete.Add(row);
}
//loop through the list to delete rows added to list<T>:
foreach (DataGridViewRow row in rowsToDelete)
        dataGridView1.Rows.Remove(row);

I select 3 items and it deletes 2 but leaves 1 behind.

How do we fix it?

UPDATED

It sounds like you want to delete the non-checked items.

What you are going to have to do is start at the bottom and go to the top, otherwise you will have extra items left over.

Example:

for (int i = DataGridView1.SelectedRows.Count - 1; -1 < i; i--)
{
   object objChecked = DataGridView1.SelectedRows[i].Cells[0].Value;
   if ((objChecked  != null) && !(bool)objChecked)
   {
     DataGridView1.Rows.RemoveAt(i);
   }
}

UPDATE 2:

Based on your comments below, this version looks at Rows instead of SelectedRows .

Check that Rows exist before beginning your loop:

if ((0 < DataGridView1.Rows.Count) && (0 < DataGridView1.Columns.Count)) 
{
  for (int i = DataGridView1.Rows.Count - 1; -1 < i; i--)
  {
    var row = DataGridView1.Rows[i];
    if ((row.Cells[0].Value != null) && (row.Cells[0].Value != DBNull.Value))
    {
      bool isChecked = (bool)row.Cells[0].Value;
      if (isChecked)
      {
        DataGridView1.Rows.Remove(row);
      }
    }
  }
}

It is a little more robust in its error checking, and removes the row by reference instead of by its index.

EDITED

You can delete by SelectedRows property.

Make sure that the MultiSelect property is set to true on your datagrid.

Then, you can utilize the SelectedRows property in the event of your choice:

This is what you need, try this code :

for (int i = dataGridView1.Rows.Count -1; i >= 0 ; i--)
{
    if ((bool)dataGridView1.Rows[i].Cells[0].FormattedValue)
    {
        dataGridView1.Rows.RemoveAt(i);
    }
}

OR

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

ASPXPAGE:

<strong>Asp.Net : Delete Multiple Records form datagridview in one time<br />
        </strong>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
            CellPadding="4" EnableModelValidation="True" ForeColor="Black">
            <Columns>
                <asp:TemplateField>
                    <EditItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="id" HeaderText="Sr No" />
                <asp:BoundField DataField="doc_name" HeaderText="Name" />
                <asp:BoundField DataField="doc_add" HeaderText="Address" />
                <asp:BoundField DataField="doc_mob" HeaderText="Mobile No" />
                <asp:BoundField DataField="doc_email" HeaderText="Email" />
            </Columns>
            <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
            <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
            <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
        </asp:GridView>
        <br />
        <asp:Button ID="Button1" runat="server" Font-Size="12pt"
            onclick="Button1_Click1" Text="Delete" />
        <br />

Code Behind Page:

SqlConnection conn = new SqlConnection(@"server=server-pc; database=HMS; integrated security=true");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            load_data();
        }
    }

   public void load_data()
    {
        SqlDataAdapter adp = new SqlDataAdapter("select * from doc_master", conn);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
    }
   protected void Button1_Click1(object sender, EventArgs e)
   {
       CheckBox ch;
       for (int i = 0; i < GridView1.Rows.Count; i++)
       {
           ch = (CheckBox)GridView1.Rows[i].Cells[0].Controls[1];
           if (ch.Checked == true)
           {
      int id = Convert.ToInt32(GridView1.Rows[i].Cells[1].Text);
      SqlCommand cmd = new SqlCommand("delete from doc_master where ID=" + id + " ", conn);
      conn.Open();
      cmd.ExecuteNonQuery();
      conn.Close();
           }
       }

       load_data();
   }

for detailed code visit:: http://www.gtuguide.com/2014/05/deleting-multiple-rows-in-gridview.html

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