我正在各个论坛上搜索,但我找不到解决方案。它应该很容易但不起作用。
我创建了名为“doctorsDataGridView”的DataGridView
,其中包含Doctors Table作为源代码。
我不想让用户添加项目,但允许删除和编辑。对于删除,首先我把这段代码:
private void doctorsDataGridView_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
// Update the balance column whenever rows are deleted.
try
{
SqlCommand cmd = new SqlCommand("DELETE FROM [Doctors] WHERE ([DoctorCode] = @code)", Welcome.con);
cmd.Parameters.Add("@code", SqlDbType.Int).Value = doctorsDataGridView.Rows[e.RowIndex].Cells["DoctorCode"].Value;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{ MessageBox.Show(ex.ToString()); }
}
private void doctorsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.doctorsBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.clincDataSet);
}
private void AllDoctors_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'clincDataSet.Doctors' table. You can move, or remove it, as needed.
this.doctorsTableAdapter.Fill(this.clincDataSet.Doctors);
}
但是当我尝试删除任何行时,它只会从DatagridView
而不是数据库中删除。
答案 0 :(得分:2)
尝试将代码放在DataGridView.UserDeletingRow Event
private void doctorsDataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
// Update the balance column whenever rows are deleted.
try
{
SqlCommand cmd = new SqlCommand("DELETE FROM [Doctors] WHERE ([DoctorCode] = @code)", Welcome.con);
cmd.Parameters.Add("@code", SqlDbType.Int).Value = doctorsDataGridView.Rows[e.RowIndex].Cells["DoctorCode"].Value;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{ MessageBox.Show(ex.ToString()); }
}
答案 1 :(得分:1)
我在这里看不出任何错误,但如果我是你,我会做以下事情:
答案 2 :(得分:1)
你确定你的sql命令执行正确吗?
MSDN:“ExecuteNoneQuery()对于UPDATE,INSERT和DELETE语句,返回值是受命令影响的行数”,因此您的ExecuteNonewQuery()必须返回1;
注意:每次加载数据时都会调用datagridview rowsremoved事件。在某种程度上,每次加载数据时都会删除现有行。所以在技术上应该召唤这个事件。
您可以使用私有布尔变量来了解何时加载以及何时加载。
private bool IsLoading { get; set; }
private void MyForm_Load(object sender, EventArgs e)
{
this.IsLoading = true;
// do stuff
this.IsLoading = false;
}
private void DataGridView_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
if (!this.IsLoading)
{
return;
}
//do stuff
}