无法删除DatagridView中的选中行 [英] Can not Delete Checked Rows in DatagridView
问题描述
你好.....
我有一个Datagridview.并且存在两列,一列是DataGridViewTextBoxColumn(第零列)
另一个是DataGridViewCheckBoxColumn(第一列)
我已经填满了Datagridview.我想删除那些已选中的行.
我的代码是...
Hello.....
I have a Datagridview . and there two columns exist ,one is DataGridViewTextBoxColumn(zeroth column)
and another is DataGridViewCheckBoxColumn(first column)
I have already filled my Datagridview. i want to delete those rows which are Checked.
my code is ...
for (int i = 1; i <= dataGridView1.Rows.Count; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells[1].Value)==true)
{
dataGridView1.Rows.RemoveAt ( i);
}
}
但是我选择的行无法删除,发生了异常,
它表明
but my selected rows could not delete , exception is occurred ,
it shows that
dataGridView1.Rows[1].Cells[1].Value =null //if I check 1st Row
为什么显示null却已被选中?
任何其他代码来删除选中的行吗?
why is shows null though it is already checked ?
any other code to delete checked rows ?
推荐答案
尝试以下操作:
Try this:
protected void btnMultipleRowDelete_Click(object sender, EventArgs e)
{
// Looping through all the rows in the GridView
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox = (CheckBox)row.FindControl("cbRows");
//Check if the checkbox is checked.
//value in the HtmlInputCheckBox's Value property is set as the
//value of the delete command's parameter.
if (checkbox.Checked)
{
// Retreive the Employee ID
int employeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
// Pass the value of the selected Employye ID to the Delete //command.
SqlDataSource1.DeleteParameters["EmployeeID"].DefaultValue = employeeID.ToString();
SqlDataSource1.Delete();
}
}
}
获取有关以下线程的完整答案:
从datgridview和数据库访问中删除行 [ ^ ]
Get complete answer on following thread:
Delete rows from datgridview and database access[^]
希望对您有所帮助:
Hope it helps:
List<int> indexes = new List<int>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[1].Value != null)
if ((bool)row.Cells[1].Value)
indexes.Add(row.Index);
}
foreach (int index in indexes)
dataGridView1.RemoveAt(index);</int></int>
for (int i = 1; i <= dataGridView1.Rows.Count; i++)
您从1开始循环.这就是为什么会出错.
从第0个索引开始循环
you are starting loop from 1. That is why you are getting error.
start for loop from 0th index
for (int i = 0; i < dataGridView1.Rows.Count; i++)
这篇关于无法删除DatagridView中的选中行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!