Adding New record - ADO.NET

D

Darryn Ross

Hi,

I am having trouble saving my new record to my access database, the dataset
gets updated fine but the new record is not being added to the database for
which it is looking at. Here is my code, any help would be appreciated.

DtlsConnection.ConnectionString = strConnectionPath ;
DtlsConnection.Open() ;

SelectDtlsCommand.CommandText = "Select * From tble" ;
SelectDtlsCommand.Connection = DtlsConnection ;
DtlsAdapter.SelectCommand = SelectDtlsCommand ;
DtlsAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey ;
DtlsAdapter.Fill(DtlsDs, "tble") ;

DataRow tblRow ;
DataTable tbl ;
tbl = DtlsDs.Tables["tble"] ;
tblRow = tbl.NewRow() ;

try {
tblRow["Code"] = txtCode.Text ;
tblRow["Name"] = txtName.Text ;
tblRow["Type"] = txtType.Text ;
tbl.Rows.Add(tblRow) ;
DtlsDs.AcceptChanges() ;
}
catch(Exception e) {
MessageBox.Show(e.Message, "Error Saving Data", MessageBoxButtons.OK,
MessageBoxIcon.Error) ;
}


Kind Regards
Darryn Ross
 
S

Stephen Muecke

Darryn

After you have added the new row, you need to call the Update method of the
DataAdaptor
Do not call AcceptChanges (this marks the row as 'unchanged' so when Update
is called, there are no 'new' rows to write back to the database!)
The Update method, if successful will in effect call AcceptChanges anyway

Stephen
 
M

Marc Scheuner [MVP ADSI]

I am having trouble saving my new record to my access database, the dataset
gets updated fine but the new record is not being added to the database for
which it is looking at. Here is my code, any help would be appreciated.
You're basically saving your new record to the data set - which is an
in-memory copy of your data. You don't ever write it back to the
database!

Check out the DataAdapter's "Update" method - that will then write
back the data to the database. You can have it run your updates
automagically, by means of providing insert, update, and delete
commands (SQL queries, or preferably stored procedures), or you can
"roll you own" if you want to.

Marc

================================================================
Marc Scheuner May The Source Be With You!
Bern, Switzerland m.scheuner(at)inova.ch
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top