I am trying to delete the selected datas from database with checkboxes. But it doesn't delete the datas. I couldn't understanf the reason. Can you have a look?
C#
int i = 0;
List ChkedRow = new List();
for (i = 0; i <= dataGridView1.RowCount - 1; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["gid"].Value) == true)
{
ChkedRow.Add(i);
}
}
if (ChkedRow.Count == 0)
{
MessageBox.Show("En az bir checkbox seçiniz!");
return;
}
foreach (int j in ChkedRow)
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
var cmdText = @"DELETE FROM gezilistemiz25 WHERE gid =" + dataGridView1.Rows[j].Cells["gid"].Value + "";
var command = new OleDbCommand(cmdText, conn);
command.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
MessageBox.Show("Kayitlar basariyla eklendi!");
Prasad RaveendranRank #320 · 7.8K reputationPosted Jun 26, 2023, 10:56 PM EDT
Please cross check whether the key value which you are sending to script is valid.
dataGridView1.Rows[j].Cells["gid"].ValueMehmet FatihRank #1,474 · 1.1K reputationPosted Jun 27, 2023, 2:08 AM EDT
Thanks for your intrest Prasad but the result is same. I am getting this error in this line.
Prasad RaveendranRank #320 · 7.8K reputationPosted Jun 27, 2023, 9:07 PM EDT
Yes. that was I mentioned. Please review thorougly this column. The same column you are trying to use for deleting a record.
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["gid"].Value) == true) . You are converting the column dataGridView1.Rows[i].Cells["gid"].Value to boolean and the same column you have used in delete query which I got confused.
Mehmet FatihRank #1,474 · 1.1K reputationPosted Jun 28, 2023, 6:50 PM EDT
I have solved porblem using the dataGridView1.Rows[j].Cells[1].Value instead of dataGridView1.Rows[j].Cells["gid"].Value
Thanks for your intrest.
Prasad RaveendranRank #320 · 7.8K reputationPosted Jun 26, 2023, 10:49 PM EDT
check the below code
int i = 0; List ChkedRow = new List(); for (i = 0; i <= dataGridView1.RowCount - 1; i++) { if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["gid"].Value) == true) { ChkedRow.Add(i); } } if (ChkedRow.Count == 0) { MessageBox.Show("En az bir checkbox seçiniz!"); return; } foreach (int j in ChkedRow) { try { using (OleDbConnection conn = new OleDbConnection(connectionString)) { conn.Open(); string cmdText = "DELETE FROM gezilistemiz25 WHERE gid = ?"; OleDbCommand command = new OleDbCommand(cmdText, conn); command.Parameters.AddWithValue("gid", dataGridView1.Rows[j].Cells["gid"].Value); command.ExecuteNonQuery(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } MessageBox.Show("Kayitlar basariyla eklendi!");