Search code examples
c#.netdataadapter

Adding a new item to a DataSet, writing it to Access DB


I'm having an issue with writing back to my Access Database (.accdb) through using a DataAdapter.

Currently, I have a Fill method which fills a DataSet Table up with data. This piece of code is currently sitting within my Form_Load().

// TODO: This line of code loads data into the 'hCAliasDataSet.Topics' table.   You can move, or remove it, as needed.
this.topicsTableAdapter.Fill(this.hCAliasDataSet.Topics);

Then I have an cmdAdd_Click() event, this is obviously to add a new row into the Topcis table that sits within the hCAliasDataSet.

// Create a new row, append it to Topics table.
DataRow DR;
DR = this.hCAliasDataSet.Tables["Topics"].NewRow();
this.hCAliasDataSet.Tables["Topics"].Rows.Add(DR); 

Next, I've created some code to caputre the input of one of the column values.

        // Capture user input
        sTopicName = Interaction.InputBox("Please Enter Topic Name", "Topic Name", null, 100, 100);
        // Set the Topic value for the new Row
        DR["Topic"] = sTopicName;

My problem, I'm assuming is here, where I call the dataAdapter to update the Topics table. I manually check the database, and there aren't any new rows created?

// Commit the changes back to the hCAlias DataBase (hcalias.accdb).
this.topicsTableAdapter.Update(this.hCAliasDataSet.Topics);

Edit: I believe I'm needing to create an INSERT query, for my TableAdapter, would this be correct?


Solution

  • The adapter should generate the insert statement automatically for you behind the scenes. Your code looks right, but it's possible that you have a constraint on one of your columns that makes it unable to save. (like a non-nullable column that you didn't specify any data for). But, you'd usually get an exception if there was a constraint that cancelled the insert.

    You can try one of these alternatives, but they're basically the same thing:

    this.topicsTableAdapter.Update(this.hCAliasDataSet); this.topicsTableAdapter.Update(DR); this.topicsTableAdapter.Insert(sTopicName); // add any other columns in here