c #datagrid复选框多删除

时间:2016-11-30 16:32:21

标签: c# sql winforms datagrid

使用此按钮删除多行检查时出现问题。它只删除第一行。 cell_dellklient是dataGridView1中复选框的名称 是复选框的真实值

请帮忙

public void button2_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        con.Open();

        object cell = row.Cells["cell_delklient"].Value;
        if (cell == "yes")
        {
            SqlCommand cmd = new SqlCommand("Delete From Klienci where Nazwa ='" + row.Cells[0].Value.ToString() + "'", con);
            cmd.ExecuteNonQuery();
            con.Close();
            wyczytywaniegridu();
        }

        con.Close();
    }
}

2 个答案:

答案 0 :(得分:0)

这是我的建议:

  public void button2_Click(object sender, EventArgs e)

{
  foreach (DataGridViewRow row in dataGridView1.SelectedRows)
        {
        string nazwa = dataGridView1.SelectedRows[row.Index].ToString();
       //Check if checkbox is checked.
        if(Convert.ToBoolean(row.Cells[0].Value))
       {
            string con = ConfigurationManager.ConnectionStrings["someConString"].ConnectionString;
                SqlConnection connection = new SqlConnection(con);
                connection.Open();
                SqlCommand cmd = new SqlCommand("Delete From Klienci where Nazwa=@Nazwa", connection);
                cmd.Parameters.AddWithValue("@Nazwa", nazwa);
                cmd.ExecuteNonQuery();
                connection.Close();
        }
 }

答案 1 :(得分:0)

我也是新人,我也遇到过这种情况。我认为你需要循环它。我曾经使用过这段代码,也使用了devexpress。所以我不确定datagridview。试着从这里得到逻辑:D

这不是答案

for (int i = 0; i < gridView1.RowCount; i++)
        {

            bool x = Convert.ToBoolean(gridView1.GetDataRow(i)["check"]);
            if (x == true)
            {                   
                   delete_data();                                      
            }
        }