954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Updating Records in Access Database C# OleDB

I'm pretty nee to all this stuff, I have no problems reading from the database but writing new records and updating fields etc is proving to be quite difficult. The following code is just meant to create a new record in a table, I started the field count at [2] as [1] is an autonumber that I presume would be generated upon creation of the record.

private string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
DataSet ds1 = new DataSet("Customer");
System.Data.OleDb.OleDbDataAdapter da;

{
connString = String.Format(connString, @"C:\Documents and Settings\Nick\Desktop\PPSP V2.0\KCH Car Rental V2.0\PPSP Car Rentals.accdb");
OleDbConnection cn = new OleDbConnection(connString);

cn.Open();

string sql = "SELECT * FROM Customer";
da = new System.Data.OleDb.OleDbDataAdapter(sql, cn);
da.Fill(ds1);

DataRow dRow = ds1.Tables["Customer"].NewRow();

dRow[2] = txtFName.Text;
dRow[3] = txtSName.Text;
dRow[4] = txtDOB.Text;
dRow[5] = txtAdd1.Text;
dRow[6] = txtAdd2.Text;
dRow[7] = txtCounty.Text;
dRow[8] = txtPostCode.Text;

ds1.Tables["Customer"].Rows.Add(dRow);

da.Update(ds1, "Customers");

cn.Close();

MessageBox.Show("Customer Added");
}

An exception is thrown at run time on the line 'DataRow dRow = ds1.Tables["Customer"].NewRow();'

Any ideas what I'm doing wrong or if theres a better way of doing what I want?

CaptainNick
Newbie Poster
2 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

What's the exception?

Ramy Mahrous
Postaholic
2,196 posts since Aug 2006
Reputation Points: 480
Solved Threads: 276
 

The exception for the highlighted line is;

NullReferenceException was unhandled

I'm not sure what part of the code this is reffering to, are there any errors or reasons you can see that would stop the code from working correctly?

CaptainNick
Newbie Poster
2 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

Debug your code to know which line raises this exception.
- Put breakpoint at ConnString and begin debugging.

Ramy Mahrous
Postaholic
2,196 posts since Aug 2006
Reputation Points: 480
Solved Threads: 276
 

You can try the following link for updation

http://csharp.net-informations.com/dataadapter/updatecommand-oledb.htm

Chan

chan_lemo
Newbie Poster
17 posts since Oct 2008
Reputation Points: 10
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You