简体   繁体   English

通过datagridview实时更新MDB数据库

[英]Realtime updating MDB database through a datagridview

I am currently trying to create a small program that takes the data from a MDB database that is displayed in a datagridview. 我当前正在尝试创建一个小程序,该程序从datagridview中显示的MDB数据库中获取数据。 The program should allow the user to modify (add, update, delete) the data in the datagridview. 该程序应允许用户修改(添加,更新,删除)datagridview中的数据。 Furthermore everything should be updated to the MDB automatically (no buttons). 此外,所有内容都应自动更新到MDB(无按钮)。 I know there are a lot of topics out there regarding this subject, however for some reason I am unable to reproduce the same results. 我知道关于该主题有很多主题,但是由于某些原因,我无法重现相同的结果。

I am able to retrieve the data from the MDB file and display it in the datagridview but I am unable to add, modify or delete data. 我能够从MDB文件中检索数据并将其显示在datagridview中,但是我无法添加,修改或删除数据。 The program keeps throwing exceptions at me but I don't understand why. 该程序不断向我抛出异常,但是我不明白为什么。

First the user has to create a database. 首先,用户必须创建一个数据库。 The database is generated automatically by code. 该数据库是通过代码自动生成的。

private void CreateNewDatabase_Click(object sender, EventArgs e)
{
    string DB_FILENAME = "c:\Test.mdb";

    // GENERATE THE ACCESS FILES, ITS TABLES AND ITS COLUMNS

    var cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0.;Data Source=" + DB_FILENAME; //Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly
    var catType = Type.GetTypeFromProgID("ADOX.Catalog");
    object o = Activator.CreateInstance(catType);
    catType.InvokeMember("Create", System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] { cnnStr });
    OleDbConnection cnn = new OleDbConnection(cnnStr);
    cnn.Open();
    var cmd = cnn.CreateCommand();

    // CREATE SCHEDULE TABLE
    cmd.CommandText = "CREATE TABLE SCHEDULE ([ID] IDENTITY PRIMARY KEY, [Day] TEXT, [Month] TEXT, [Year] TEXT, [IMS] TEXT, [Customer] TEXT, [Short Description] TEXT, [Long Description] TEXT, [Delivery Ticket Number] TEXT, [Returned] TEXT)";
    cmd.ExecuteNonQuery();

    cmd.CommandText = "INSERT INTO SCHEDULE ([ID]) VALUES (1)";
    cmd.ExecuteNonQuery();

    // DISPOSE OF THE VARIABLES USED
    cnn.Close();
    cnn.Dispose();
    cmd.Dispose();

}

Once the database has been created it is used in a windows form with a datagridview in it. 创建数据库后,将以Windows窗体使用其中包含datagridview的数据库。

public void Initialize()
{

    Con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sttngs.DBloc);
    Con.Open();

    // TRY TO OPEN THE DATABASE FILE AND POPULATE THE DATAGRIDVIEW
    da = new OleDbDataAdapter("SELECT [Day], [Month], [Year], [IMS], [Customer], [Short Description], [Long Description], [Delivery Ticket Number], [Returned] FROM SCHEDULE",Con); // WHERE [Returned] = '" + "NO' ", Con);

    // POPULATE cBuilder
    cBuilder = new OleDbCommandBuilder(da);
    ScheduleData = new DataTable();
    da.Fill(ScheduleData);

    if (ScheduleData.Rows.Count > 0)
    {
       BindingSource BDS = new BindingSource();
       BDS.DataSource = ScheduleData;
       this.dataGridView.DataSource = BDS;        
    }
}

Once the data in the datagridview is changed (handled by the CellValidating event) the data should be updated in the MDB. 一旦更改了datagridview中的数据(由CellValidating事件处理),就应该在MDB中更新数据。

 private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
 {
     if (ScheduleData.GetChanges() != null)
     {
        dataGridView.EndEdit();
        da.Update(ScheduleData);
        ScheduleData.AcceptChanges();
     }
 }

The code is pretty straight forward but for some reason I am unable to figure out why the data in the MDB is not updated. 该代码非常简单,但是由于某些原因,我无法弄清楚为什么MDB中的数据没有更新。 I have been stuck for a while now so any help would be great! 我已经被卡住了一段时间了,所以任何帮助都会很棒!

One thing I can see that will cause an issue is that when you setup your commandbuilder you are not requesting the relevant UPDATE, DELETE & INSERT commands. 我可以看到的一件事是,当您设置Commandbuilder时,您没有在请求相关的UPDATE,DELETE和INSERT命令。

When you generate the command builder like this :- 当您生成这样的命令生成器时:-

cBuilder = new OleDbCommandBuilder(da);

Follow up with :- 跟进:-

cBuilder.GetUpdateCommand();
cBuilder.GetInsertCommand();
cBuilder.GetDeleteCommand();

You may need to declare all of this in Cell Validating, I'm unsure. 我不确定,您可能需要在单元验证中声明所有这些信息。 Give It a try. 试试看。

Look this MSDN article over, its for the SQLcommamdbuilder, but the same rules apply :- 查看此MSDN文章,它适用于SQLcommamdbuilder,但适用相同的规则:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommandbuilder.aspx http://msdn.microsoft.com/zh-CN/library/system.data.sqlclient.sqlcommandbuilder.aspx

Also, You have no open connection to the Data Adapter as you try to update it :- 另外,尝试更新它时,您没有与数据适配器的开放连接:-

if (ScheduleData.GetChanges() != null)
     {
        dataGridView.EndEdit();

        //Open a connection Here
        da.Update(ScheduleData);

        ScheduleData.AcceptChanges();
     }

Your SQL String is incorrect, try :- 您的SQL字符串不正确,请尝试:-

"SELECT (Day, Month, Year, IMS, Customer, Short Description, Long Description, Delivery Ticket Number, Returned) FROM [SCHEDULE]"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM