开发者

Exception when adding a record to an Access 2007 database in c#

I'm trying to add a record to an Access 2007 database using c# but I get an exception.

Here's my code, the database is called hms and the table is called login

DataSet ds = new DataSet();

System.Data.OleDb.OleDbConnection con;
DataRow dRow;
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" +  Application.StartupPath + "\\hms.mdb";
string sql = "select * from login";
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);

System.Da开发者_开发技巧ta.OleDb.OleDbCommandBuilder cb;
cb = new System.Data.OleDb.OleDbCommandBuilder(da);

dRow = ds.Tables[1].NewRow(); //I get an error on this line

dRow[1] = "sakest";
ds.Tables["hms"].Rows.Add(dRow);
da.Fill(ds, "hms");
da.Update(ds, "hms");

MessageBox.Show("new enrtry ");


What error message are you getting exactly. At a guess I would say that you are requesting a table that does not exist, your query only returns 1 table so it's index would be 0

Try this:

dRow = ds.Tables[0].NewRow();


As far as I can tell, the issue with your code is that you create your DataSet (ds), but never fill it.

You need something similar to this:

using (OleDbConnection con = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\hms.mdb"))
{
    con.Open();
    string sql = "select * from login";
    using (OleDbDataAdapter da = new OleDbDataAdapter(sql, con))
    {
        DataSet ds = new DataSet();
        da.Fill(ds);

        DataRow dRow = ds.Tables[0].NewRow();
        dRow[1] = "sakest";
        ds.Tables["hms"].Rows.Add(dRow);
        da.Fill(ds, "hms");
        da.Update(ds, "hms");

        MessageBox.Show("new enrtry ");
    }
}

Basically, the bit you're after is the da.Fill(ds) line, and the change from ds.Tables[1].NewRow() to ds.Tables[0].NewRow().

Note: I've re-jigged the code so as to show you how to wrap the OleDbConnection and OleDbDataAdapter in using's so as to ensure that they're cleaned up by the CLR properly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜