VinceG
VinceG

Reputation: 77

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

this is my data grid view

enter image description here

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");
        }

Upvotes: 0

Views: 913

Answers (1)

Caius Jard
Caius Jard

Reputation: 74660

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)
    {

Upvotes: 1

Related Questions