1

我在每个论坛上都在搜索,但找不到解决方案。这应该很容易,但它不起作用。

我创建了DataGridView名为“doctorsDataGridView”的以 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而不是从数据库中删除。

4

3 回答 3

3

尝试将您的代码放入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()); }
}
于 2013-02-02T23:36:37.220 回答
1

我在这里看不出任何问题,但如果我是你,我会这样做:

  • 打开 SQL Server 探查器并首先查看是否有任何东西到达 SQL Server
  • 检查您的数据库引用?Doctors 表是否被其他表引用?也许这会阻止您删除数据
  • 使用调试器单步执行代码并在执行 cmd.ExecuteNonQuery() 之前检查 SQL 语句 - 尝试在 SSMS 中手动执行相同的语句
于 2013-02-02T19:39:10.840 回答
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
}
于 2013-02-02T23:06:25.837 回答