c# - 如何在ce中创建空数据库并用datagridview显示

所以,我的代码

if (System.IO.File.Exists(fileName))
        {
            System.IO.File.Delete(fileName);
        }
        SqlCeEngine en = new SqlCeEngine(connectionString);
        en.CreateDatabase();

        SqlCeConnection cn = new SqlCeConnection(connectionString);
        if (cn.State == ConnectionState.Closed)
            cn.Open();
        string sql = "create table EnergyMain(id int not null, date datetime not null, totalamount float)";
        SqlCeCommand cmd = new SqlCeCommand(sql, cn);
        cmd.ExecuteNonQuery();

        SqlCeCommand tbltodgv = new SqlCeCommand("EnergyMain", cn);
        tbltodgv.CommandType = CommandType.TableDirect;
        SqlCeResultSet rs = tbltodgv.ExecuteResultSet(ResultSetOptions.Scrollable | ResultSetOptions.Updatable);
        dgvMain.DataSource = rs;

        cn.Close();

此代码使用一个空表创建简单的空数据库。当我按下表单上的按钮时,它会创建它。但是当我第二次按下它时它会写错误
Invalid attempt to call method Updatable when SqlResultSet is closed.

我怎样才能根据需要多次创建数据库

最佳答案

将datagridview绑定(bind)到结果集时,不要关闭底层连接,所以去掉cn.Close()

https://stackoverflow.com/questions/9887037/

相关文章:

android - 无法在 android opencv 2.3 中导入 ml.h

compiler-errors - 使用ROSE编译器框架的g++编译器错误

visual-studio-2010 - Visual Studio 2010 C++发行模式问题

c++ - 如何在 Windows XP 上正确安装 ffmpeg?

javascript - 编译CoffeeScript

android - 在Eclipse上调试Android应用时出错

ios - 由于未捕获的异常 'NSInvalidArgumentException' 错误而终止应

c++ - 使用Visual Studio Express和SDL2在Windows中破坏了SDL_

triggers - 触发编译错误(插入)

android - Debian Sid 上的 Android 内核总是出错