从MySQL数据库中选定的Datagridview中删除行的问题

时间:2016-08-02 08:46:47

标签: c# c++ mysql-workbench windows-forms-designer

DataGridView删除选定的行后,我无法更新MySQL数据库。运行ExecuteNonQuery()时,我收到的错误是:

  

System.Invalid.Operation.Exception:Connection必须有效且打开。

但是我已经建立了正确的连接。我仍然遇到问题。

我的代码如下:

private: System::Void button9_Click(System::Object^  sender, System::EventArgs^  e)
{
    String^ constring = L"datasource=localhost;port=3306;username=****;password=********";
    MySqlConnection^ conDataBase = gcnew MySqlConnection(constring);
    conDataBase->Open();
    try 
    {
        if (MessageBox::Show("Sure you wanna delete?", "Warning", MessageBoxButtons::YesNo) == System::Windows::Forms::DialogResult::Yes)
        {
            for each(DataGridViewCell^ oneCell in dataGridView1->SelectedCells)
            {
                if (oneCell->Selected) {
                    dataGridView1->Rows->RemoveAt(oneCell->RowIndex);
                    MySqlCommand^ cmdDataBase1 = gcnew MySqlCommand("Delete from Dinslaken_DB.Configuration where Memory=" + dataGridView1->CurrentRow->Index +"");
                    cmdDataBase1->ExecuteNonQuery();
                    //sda->Update(dbdataset);
                }   
            }           
        }
    }
    catch (Exception^ex)
    {
        MessageBox::Show(ex->ToString());
    }
}

1 个答案:

答案 0 :(得分:0)

您已创建命令对象

MySqlCommand^ cmdDataBase1 = gcnew MySqlCommand("Delete from Dinslaken_DB.Configuration where Memory=" + dataGridView1->CurrentRow->Index +"");

但您尚未设置其命令属性。很可能上面的命令构造函数的第二个参数应该是连接。检查一下。

所以你的命令构造函数应该是:

MySqlCommand^ cmdDataBase1 = gcnew MySqlCommand("Delete from Dinslaken_DB.Configuration where Memory=" + dataGridView1->CurrentRow->Index +"", conDataBase);

也不要忘记关闭连接。