Я пытаюсь удалить строку, которую пользователь выбирает в DataGridView в приложении C # WinForms (подключенном к локальной БД, в которой уже есть записи).
Я реализовал приведенный ниже код, и естьошибок нет, но удаление никогда не происходит (даже несмотря на то, что сообщение показывает, что запись была «удалена», что не соответствует действительности, поскольку запись остается в DataGrid)
Обратите внимание, что функция удалениянаходится в функции поиска - см. код ниже.
public void DisplayData()
{
string ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename= C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\Library System Project.mdf ;Integrated Security=True;Connect Timeout=30";
string Query = "select * from Customers";
SqlConnection DBCon = new SqlConnection(ConnectionString);
SqlCommand DBCommand = new SqlCommand(Query, DBCon);
SqlDataReader DBReader;
try
{
DBCon.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(DBCommand);
da.Fill(dt);
dgv_CustomerDetails.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// *** If you're going to be opening a connection be sure to close it ***
// *** Finally blocks work well for this ***
DBCon.Close();
}
}
private void SearchCustomerRecordForm_Load(object sender, EventArgs e)
{
DisplayData();
}
private void btnDeleteCustomerRecord_Click(object sender, EventArgs e)
{
string ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename= C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\Library System Project.mdf ;Integrated Security=True;Connect Timeout=30";
int rowIndex = dgv_CustomerDetails.CurrentCell.RowIndex;
string Query = "delete from Customers where CustomerName = '"+ dgv_CustomerDetails.CurrentCell(rowIndex) +"'";
SqlConnection DBCon = new SqlConnection(ConnectionString);
SqlCommand DBCommand = new SqlCommand(Query, DBCon);
SqlDataReader DBReader;
try
{
DBCon.Open();
DBReader = DBCommand.ExecuteReader();
MessageBox.Show("Customer record removed from the system.", "Library System", MessageBoxButtons.OK);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// *** If you're going to be opening a connection be sure to close it ***
// *** Finally blocks work well for this ***
DBCon.Close();
DisplayData();
}
}