private void button3_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in dataGridView1.Rows)
{
if (bool.Parse(item.Cells[0].Value.ToString()))
{
MessageBox.Show("Selected Rows : " + item.Cells[0].RowIndex.ToString());
}
}
}
答案 0 :(得分:0)
尝试以下代码
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in gvDetails.Rows)
{
//Finiding checkbox control in gridview for particular row using below syntax
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chkSelect");
//Condition to check checkbox selected or not
if (chkdelete.Checked)
{
//Getting UserId of particular row using datakey value
int usrid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value);
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("delete from UserDetails where UserId=" + usrid, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
BindUserDetails();
}
如果您想了解更多信息,请参阅以下链接
答案 1 :(得分:0)
单击button3时,将执行以下事件处理程序。它首先使用LINQ查询从DataGridView获取已检查(选定)的行,然后显示确认消息框。
如果用户单击是按钮,则会对所选(已选中)行执行循环,并使用Id字段从数据库表中删除逐个记录。
注意:这里采取的数据库查询是让OP了解他是如何实现它的,因为OP在他的帖子中没有提及任何内容,这将是一种更好地解释的方式
private void button3_Click(object sender, EventArgs e)
{
List<DataGridViewRow> selectedRows = (from row in dataGridView1.Rows.Cast<DataGridViewRow>()
where Convert.ToBoolean(row.Cells["checkBoxColumn"].Value) == true
select row).ToList();
if (MessageBox.Show(string.Format("Do you want to delete {0} rows?", selectedRows.Count), "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
foreach (DataGridViewRow row in selectedRows)
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@CustomerId", row.Cells["CustomerId"].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
this.BindGrid();
}
}
答案 2 :(得分:0)
试试这段代码,它对我有用:
int j = 0;
int countRows = dataGridView1.Rows.Count;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i]
.Cells[0].Value) == true)
{
dataGridView1.Rows.RemoveAt(i);
}
i = i - 1;
j = j + 1;
if (j == countRows)
{
break;
}
}
答案 3 :(得分:-2)
当您删除一行时,首先删除该行,datagrid行的大小的新值总计减去1,因此我使用的是i - 。为什么要使用条件&#34; if(i&lt; dataGridView1.Rows.Count -1)&#34;因为只有当行[i]为1而不是0时才需要减去。
您可以使用try catch而不是条件。
祝你好运! private void button3_Click(object sender, EventArgs e)
{
for (int i = 0; i <= dataGridView1.Rows.Count -1; i++)
{
if ((bool)dataGridView1.Rows[i].Cells[0].Value == true)
{
dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
if (i < dataGridView1.Rows.Count -1)
{
i--;
}
}
}
}