【发布时间】:2019-10-13 17:33:39
【问题描述】:
我正在尝试删除用户在 C# WinForms 应用程序的 DataGridView 中选择的行(连接到已经有记录的本地数据库)。
我已经实现了下面的代码,并且没有错误,但是删除从未被拾取(即使消息框显示一条记录已被“删除”,这是不正确的,因为该记录仍保留在 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();
}
}
【问题讨论】:
标签: c# sql visual-studio datagrid sql-delete