如何使用复选框删除所选的datagrideview行 [英] how to delete selected row of datagrideview using checkboxes

查看:140
本文介绍了如何使用复选框删除所选的datagrideview行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题当我从gridview中选择3个选中的行时,使用复选框删除2行,最后一行不删除

解决方案是什么?

我写这个类

my problem when I select 3 selected rows from gridview using checkboxes remove 2 rows and the last row don't remove
what's the solution?
I write this class

 public static bool DeletePayments(int id)
{                     
       bool b;

       string strconn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\..\Salaries.accdb";
       OleDbConnection conn = new OleDbConnection(strconn);

       if (conn.State == ConnectionState.Closed)
       {
              conn.Open();
       }

       OleDbCommand cmd = new OleDbCommand("DELETE FROM Payments WHERE Payment_ID =@id;", conn);

      cmd.Parameters.Add(new OleDbParameter("@id", id));

       int i = cmd.ExecuteNonQuery();

       if (i <= 0)
              b = false;
       else
              b = true;
       conn.Close();
       return b;
}



和button_click事件我写的


and at button_click event I write

private void button3_Click(object sender, EventArgs e)
{
       for (int i = 0; i < GridViewPays.Rows.Count; i++)
       {
              if (GridViewPays.Rows[i].Cells[0].Value != null)
              {
                     if ((bool)GridViewPays.Rows[i].Cells[0].Value == true)
                     {
                            GridViewPays.Rows.RemoveAt(i);

                            if (PaymentsMgr.DeletePayments(int.Parse(GridViewPays.CurrentRow.Cells["Payment_ID"].Value.ToString())))
                            {
                                   GridViewPays.EndEdit();
                            }
                     }
              }
       }
}

推荐答案

问题是因为你已经使用
for (int i = 0; i < GridViewPays.Rows.Count; i++)



说你的DGV有4行:


Say your DGV has 4 rows :

0  Row 1
1  Row 2
2  Row 3
3  Row 4



如果删除第一行(index = 0),DGV必须向上洗牌其余行 - 如这:


If you delete the first row (index = 0) the DGV will have to "shuffle" the remaining rows upwards - like this:

0  Row 2
1  Row 3
2  Row 4



所以你的循环移动到它的下一个值(index = 1)并删除第3行的内容,其余的则被洗牌。


So your loop moves onto its next value (index = 1) and deletes what was Row 3 and the rest get shuffled up.

0  Row 2
1  Row 4



从列表/网格中删除/等等,如果你打算在循环中使用项目的索引,总是从列表的底部开始并向上(或向后)工作。这样行不会向上移动,它们保持原来的位置。例如


When deleting from lists / grids / etc, if you are going to use the index of an item in a loop, always start at the bottom of the list and work upwards (or backwards). That way the rows do not get shuffled upwards, they stay where they were originally. E.g.

for (int i = GridViewPays.Rows.Count; i >= 0; i--)

这篇关于如何使用复选框删除所选的datagrideview行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆