2016-11-30 66 views
0

我有問題,當我用此按鈕刪除multichecked行。它只刪除第一行。 cell_dellklient是dataGridView1複選框的名字 肯定是複選框的真正價值c#datagrid複選框多刪除

請幫

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

你爲什麼在每次迭代打開連接一次,關閉它兩次每次迭代? –

回答

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 [email protected]", connection); 
       cmd.Parameters.AddWithValue("@Nazwa", nazwa); 
       cmd.ExecuteNonQuery(); 
       connection.Close(); 
     } 
} 
+0

謝謝你的回覆。對不起,但我入門。我試過這個,但即時通訊接收:'DataGridView'不包含'DataKeys'的定義,並且沒有擴展方法'DataKeys'接受類型'DataGridView'的第一個參數可以找到(你是否缺少使用指令或程序集引用? )\t在Visual Studio 2015中使用Windows窗體。 –

+0

檢查更新。我還沒有測試過。 – Auguste

+0

我收到FindControl的同樣的錯誤,就像我爲DataKeys所做的那樣:( –

0

IAM還新,我遇到這種情況也。我認爲你需要循環它。我曾經使用這個代碼,也使用devexpress。所以我不清楚datagridview。試圖從這裏得到的邏輯:d

這不是一個答案

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

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