简体   繁体   中英

Delete a record from a database and DataGridView at the same time using C#

I have a DataGridView that extracts data from the database linked to SQL Server Manangement Studio and shows it on the DataGridView .

I have a Delete button that allows a user to delete a specific record using this code:

string SQLdelete = "DELETE FROM User WHERE Id = @RowID";

SqlParameter RowParameter = new SqlParameter();

SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = SQLdelete;

RowParameter.ParameterName = "@RowID";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowIndex + 1;

deleteRecord.Parameters.Add(RowParameter);

deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
deleteRecord.Connection.Close();

The problem is that after deleting multiple records, I think the RowID gets mixed up and for example if I have a Data ID from 6-8 (That's their IDs that are linked to the delete query) , it doesn't get deleted and sometimes when I click on the 3rd record , the 1st record gets deleted.

I don't know if I'm clear enough but if you want me to add any information I'll let you know.

I think it has to do with the DataGridView 's RowID and my table's ID ; they get mixed up when I delete many records.

Can someone tell me what should I add in my delete code to avoid this problem?

Thank you so much!

Here you need to delete the records using the "ID" present in the table.

Means you need to bind the "ID" to datagridview, and "ID" present in the datagridview need to pass as parameter to query, and needs to delete the record.

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