Dafuqisthis
Dafuqisthis

Reputation: 1

Delete SQL row and change Id

I am making a C# tool that connects to a SQL database to manage users for another program I created. I'm displaying the Users in a ListBox, and I can add/delete users. Things got weird after I deleted some profiles, and I thought that could have something to do with how I delete the row from the database. I'm using an Id that automatically increases with every new user creation. This is my code for deleting from the database:

using (conn = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand("DELETE FROM myDatabase WHERE Id = '" + (listBox1.SelectedIndex + 1) + "'", conn))
{
    conn.Open();
    command.ExecuteNonQuery();
}

and this is how I load the users into my listbox:

using (conn = new SqlConnection(connectionString))
using (SqlDataAdapter sqlAdapt = new SqlDataAdapter("SELECT * FROM myDatabase", conn))
{
    DataTable dataTable = new DataTable();
    sqlAdapt.Fill(dataTable);
    listBox1.DisplayMember = "Name";
    listBox1.ValueMember = "Id";
    listBox1.DataSource = dataTable;
}

How can I delete the correct row from the database?

Upvotes: 0

Views: 1558

Answers (2)

TTomer
TTomer

Reputation: 356

"DELETE FROM myDatabase WHERE Id = '" + (listBox1.SelectedIndex + 1) + "'"

I'm not sure about mySQL, but it looks like you pass a string instead of an int. When you pass a parameter as a number you should remove the " ' ". so, it will look like:

"DELETE FROM myDatabase WHERE Id = " + (listBox1.SelectedValue)

Upvotes: -1

Steve
Steve

Reputation: 216333

You should use the property SelectedValue to find your ID not the SelectedIndex

if(listBox1.SelectedValue != null)
{
    int userID = Convert.ToInt32(listBox1.SelectedValue);
    using (conn = new SqlConnection(connectionString))
    using (SqlCommand command = new SqlCommand("DELETE FROM myDatabase WHERE Id = @uid", conn))
    {

        conn.Open();
        command.Parameters.Add("@uid", MySqlDbType.Int32).Value = userID;
        command.ExecuteNonQuery();
    }
}

The problem with SelectedIndex is that this value goes from 0 to the max number of items in the listbox. This value has nothing to do with the ID of your user automatically calculated by your database. (After just one delete and one add these value are out of synch)

Note also that an sql text should never built using string concatenation. This is a well know security problem called Sql Injection.

Upvotes: 3

Related Questions