如何删除数据网格视图中选中复选框的行?

我正在使用C#.NET 2.0 Visual Studio 2005。

我遇到了奇怪的问题。

有一个简单的窗口forms,只有一个DataGridView,其中column1是复选框(DataGridViewCheckboxColumn)

然后,如果选中单元格中的复选框,我想删除选中的行。

声音非常简单,但它不会以某种方式删除所有已检查的行,我无法确定它为什么会以这种方式运行。

例如,我有5行并检查每行中的所有复选框,但它只删除3行。 谁看过这个吗? 这是一个错误还是我做错了什么?

namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //when I click the button, all checked row should be removed private void button1_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.Rows) { if ((bool)row.Cells[0].Value) { dataGridView1.Rows.Remove(row); } } } } } 

当一行被删除时,它会发生行计数递减,所以如果你把你的代码放在for循环中并反向运行它会工作正常看看:

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

你在迭代它时修改了一个集合。

使用删除列表,然后删除行。

您正在迭代它时修改集合。 试试这样吧

 List toDelete = new List(); foreach (DataGridViewRow row in dataGridView1.Rows) { if (row.Cells[0].Value == true) { toDelete.Add(row); } } foreach (DataGridViewRow row in toDelete) { dataGridView1.Rows.Remove(row); } 

这个解决方案给出了一点错误,我修复了添加1行:)

 List toDelete = new List(); foreach (DataGridViewRow row in dataGridView1.Rows) { bool s = Convert.ToBoolean(row.Cells[0].Value) //added this line if (s == true) { toDelete.Add(row); } } foreach (DataGridViewRow row in toDelete) { dataGridView1.Rows.Remove(row); } 

@Chen Kinnrot,绝对是钱! 在运行函数时,您将始终只删除n%2行,因此如果您有10行,那么您将删除5,101将是51,等等。迭代集合以查找检查哪些复选框然后删除它们行。 更好的解决方案是将事件附加到单击button1时自动运行的复选框。

 ASPXPAGE: Asp.Net : Delete Multiple Records form datagridview in one time


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(); }

有关详细代码,请访问: http : //www.gtuguide.com/2014/05/deleting-multiple-rows-in-gridview.html