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?