【问题标题】:Problems in deleting rows from selected Datagridview in MySQL database从 MySQL 数据库中的选定 Datagridview 中删除行的问题
【发布时间】:2016-12-07 12:45:53
【问题描述】:

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

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

但是我已经建立了正确的连接。我还是有问题。

我的代码如下:

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());
    }
}

【问题讨论】:

  • 花点时间阅读帮助中心的editing help。 Stack Overflow 上的格式设置与其他站点不同。您的帖子看起来越好,其他人就越容易阅读和理解它。
  • 对于 .Net 使用 C# 而不是 C++。 C++.Net 的语法非常难看。不要惩罚自己。

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


【解决方案1】:

你已经创建了命令对象

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);

也不要忘记关闭连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 2016-08-02
    相关资源
    最近更新 更多