简体   繁体   中英

How do I delete selected row in datagridview in database?

The only problem with the code is that when there is a same Id, it will delete that as well, which is not really delete the row I selected in datagridview.

       private void Delete_Button_Click(object sender, EventArgs e)
    {

        if (dataGridView1.SelectedRows.Count > 0)
        {
            int Index = dataGridView1.CurrentCell.RowIndex;
            if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string delete = dataGridView1.Rows[Index].Cells[0].Value.ToString();
                SqlCeCommand cmd = new SqlCeCommand("delete from Contact_List where Id "+ delete + "'", con);
                con.Open();
                cmd.ExecuteNonQuery();
                MessageBox.Show("Information Deleted.....");
                filldata();
            }
        }
        else
        {
            MessageBox.Show("Please Select a Row");
        }
        con.Close();
    }

Can anyone help me ? so this code will only delete the row that i selected and also the database as well.

Thanks! and sorry for bad English

First of all, use parameterized queries. Second of all, you need to either put a key field in your gridview (even if you just have it in a hidden column) or else rework your delete statement to include enough columns that it deletes just the row you want. And if you can't determine a unique row in the table based on the values in a selected row in the grid view, you're basically out of luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM