简体   繁体   中英

How do I get the id of the selected row from my database in a datagridview control?

this is my data grid view

在此处输入图像描述

I want to get the ID when a row is selected but when I select a row and click delete it doesn't seem to get the id of that row and goes for the else statement instead. here is my code. why does it not get the ID when selected?

MySqlCommand cmd = conn.CreateCommand();
        int ID = 0;

        if ( ID != 0)
        {
            cmd = new MySqlCommand("delete from vehicle where ID=@id", conn);
            conn.Open();
            cmd.Parameters.AddWithValue("@id", ID);
            cmd.ExecuteNonQuery();
            conn.Close();
            MessageBox.Show("Record Deleted Successfully!");
            int rowIndex = dataGridView1.CurrentCell.RowIndex;
            dataGridView1.Rows.RemoveAt(rowIndex);
        }
        else
        {
            MessageBox.Show("Please Select Record to Delete");
        }

Your ID will never be anything other than 0 at the time the if is tested, so your code will always go for the else

    int ID = 0;

    if ( ID != 0)
    {

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