UPDATING Dataset Fails? - c#

According to this article : http://msdn.microsoft.com/en-us/library/xzb1zw3x.aspx , after I insert/change data in the dataset, I need to call the UPDATE to synchronize my database data with the dataset data.
My problem is this:
I have created a dataset called dataset1.xsd and then I create a new TableAdapter to do my INSERT query with, and THEN I need to somehow let my database know that the stuff in dataset has changed.
DataSet1TableAdapters.reservationsTableAdapter ta = new DataSet1TableAdapters.reservationsTableAdapter();
ta.Insert(LastName,Arrival,Departure); // this is where I do the INSERT query
Now I should update the dataset, right? How do I do this? The article I posted above suggests doing something like this:
ta.Update(DataSet1.reservationsDataTAble);
However, I can't do this because:
Error - 'myproject.DataSet1.reservationsDataTable' is a 'type', which is not valid in the given context.
I tried declaring a new Dataset1 DataTable, and then updating that, but it still won't show any changes in my database.
I KNOW, however, that the changes are saved in the DataSet, because when I fill a new datatable later, the record is there.
EDIT: Thanks to the comments, below, I tried doing this for a change:
DataSet1.reservationsDataTable NDT = new DataSet1.reservationsDataTable();
DataSet1TableAdapters.reservationsTableAdapter ta = new DataSet1TableAdapters.reservationsTableAdapter();
ta.Insert(LastName,Arrival,Departure);
ta.Fill(NDT);
ta.Update(NDT);
... and I could see (in the debugger) that the NDT datatable DID in fact contain the data that was "INSERTED" and then filled into the data table.
However, the ta.Update(NDT); still did not update my database...

I assume that However, the ta.Update(NDT); still did not update my database means that no sql-insert is executed and that yo get no exception.
does this work for you?
var myDataSet1 = new DataSet1();
var newReservation = myDataSet1.reservations.NewRow();
newReservation.LastName=...
newReservation.Arrival=...
newReservation.Departure=...
myDataSet1.reservations.AddreservationsRow(newReservation);
var ta = new DataSet1TableAdapters.reservationsTableAdapter();
ta.Update(myDataSet1.reservations);

Related

How can I check if data in dataset is updated and catch updated data? C#

I have timer-function. It handles data from sql database every N time (it's doesn't matter actually what time). The subsequent algorithm does not work. Or I don't know how to make it work.
I put data into Dataset.
const string query = "SELECT id FROM SomeTable LIMIT 100";
await using var cmd = new MySqlCommand(query, connection);
var sqlAdapter = new MySqlDataAdapter(cmd);
sqlAdapter.TableMappings.Add("Table", "SomeTable");
sqlAdapter.Fill(_mapping);
_mapping.AcceptChanges();
Where _mapping is dataset.
If this is the first filling of the dataset, then just fill it.
If this is not the first filling, then try to update the data in it. I tried to use sqlAdapter.Update(_mapping). But it doesn't update any data Or I cant get updated data. I tried fill it again and check _mapping.hasChanges(DataRowState.Modified | DataRowState.Added))
But it hasn't any changes.
So how can I fill dataset and catch changed or added rows while I get data from Database?
Or may be I need to use another things like dataTable or something else?

Insert rows on a existing dataset

I have a dataset called "titulos" and have 1 table there called "tb"
with the columns with the name "titulo","titulo 2" and "titulo3".
I'm trying to do an insertion of rows in the event onclick of a button
but for some reason my code doesn't work!
My dataset is on a xsd file and I am using visual studio 2013 with c#.
I already tried this code but I don't know how to apply in my situation:
NorthwindDataSet.CustomersRow newCustomersRow =
northwindDataSet1.Customers.NewCustomersRow();
newCustomersRow.CustomerID = "ALFKI";
newCustomersRow.CompanyName = "Alfreds Futterkiste";
northwindDataSet1.Customers.Rows.Add(newCustomersRow);
The problem is that shows an error saying it does not recognize the dataset...
The erros is : "The name " Ds_Admissibilidade" does not exist in the current context
A DataSet is a disconnected copy of the data. It forgets if the data originated from database, an xml file or anything else. When you add rows to the DataSet, you only change the in-memory copy, not the original source.
You need some mechanism to update the source. For databases, a table adapter or dataadapter will do this for you. For a file source, you need to serialize the DataSet to the file, much the reverse of the way you read in in first place.
Hope this helps :)
DataRow newRow = titulos.Tables["tb"].NewRow();
newRow["titulo1"] = "titulo1";
newRow["titulo2"] = "titulo2";
newRow["titulo3"] = "titulo3";
titulos.Tables["tb"].Rows.Add(newRow);
Make sure you're setting all the values of the non nullable parameters. If you're using another instance of the dataset "titulos" use ImportRow instead of Add function.

How to access data in a DataSet within current project?

I'm attempting to access a basic table from a local database in my Windows Forms project. I seem to have created the database correctly, and imported the dataset as expected as it displays in my Solution Explorer.
However, I am stuck on how to actually access the data within my database. I've attempted many different solutions but I cannot seem to get anywhere.
Here is what I've accomplished so far:
Solution Explorer Screenshot
But I cannot figure out how to make queries to the dataset, whether it's selecting, updating, or deleting rows.
The closest I've come to getting the data is from the code here:
InventoryDatabaseDataSet context = new InventoryDatabaseDataSet();
var inv = context.Tables["Inventory"];
var all = inv.Select();
But it doesn't return any seemingly valid data.
How do I go about making queries to my dataset? I understand Linq is the common method of making queries, but I don't understand how to get to the point of being able to do such a thing.
Any help would be greatly appreciated, thanks!
The DataSet item in the Solution Explorer represents a number of types. Just as String, Int32 and Form are types, so InventoryDatabaseDataSet is a type. Just like other types, you create an instance in code and then use it.
You will also find that those types that are components have been added to your Toolbox and can be added to forms in the designer, just like other controls and components.
You can also drag items from the Data Sources window and have the designer generate appropriate objects and code. For instance, if you drag a table from the Data Sources window to a form, it will generate a DataSet to store the data, a table adapter to retrieve data from the database and save changes back, a DataGridView to display the data, a BindingSource to link between the DataTable and the DataGridView and a BindingNavigator to navigate the data.
If you do use the designer then you'll see code generated to retrieve data by calling Fill on the table adapter and save changes by calling Update. If you want to do it in code yourself then you can do it something like this to retrieve:
var data = new InventoryDatabaseDataSet();
using (var adapter = new InventoryTableAdapter())
{
adapter.Fill(data);
}
this.InventoryBindingSource.DataSource = data.Inventory;
this.InventoryDataGridView.DataSource = this.InventoryBindingSource;
and this to save:
this.InventoryBindingSource.EndEdit();
var data = (InventoryDataTable) this.InventoryBindingSource.DataSource;
using adapter = new InventoryTableAdapter())
{
adapter.Update(data);
}
After storing data in DataSet,DataSet is read through DataTable object.
Similarly object of DataRow is used to read the row of a table.
Following is the sample code
InventoryDatabaseDataSet ds = new new InventoryDatabaseDataSet();;
DataTable dt = new DataTable();
da.SelectCommand = new SqlCommand(#"SELECT * FROM FooTable", connString);
da.Fill(ds, "FooTable");
dt = ds.Tables["FooTable"];
foreach (DataRow dr in dt.Rows)
{
MessageBox.Show(dr["Column1"].ToString());
}

A DataTable named 'Table' already belongs to this DataSet

when i am adding second table(dtResult) to data set that time it's giving error
A DataTable named 'Table' already belongs to this DataSet.
DataTable dtSession = new DataTable();
DataTable dtResult= new DataTable();
dtResult.TableName = "A";
dtSession.TableName = "B";
dtSession = objOpt.GetSearchDetails().Copy();
ds.Tables.Add(dtSession);
dtResult = objOpt.Search_Synchronous().Copy();
ds.Tables.Add(dtResult);
Thanks in advance
You need to name the tables after getting the copy from your method and before adding it to the DataSet.
DataTable dtResult= new DataTable();
dtSession = objOpt.GetSearchDetails().Copy();
dtSession.TableName = "B";
ds.Tables.Add(dtSession);
dtResult = objOpt.Search_Synchronous().Copy();
dtResult.TableName = "A";
ds.Tables.Add(dtResult);
Since you are getting the copy from your methods objOpt.GetSearchDetails().Copy() and objOpt.Search_Synchronous().Copy(), they are overwriting the names assigned to the table previously, and both of these are returning the table with name Table, that is why you are getting this error
I was getting this exception today, but it had nothing to do with adding a DataTable.
I have an ASP.Net Core WebApi, and in the Post and Put endpoints, I was attempting to save/update the new record and also search in the database (in the same table) for an existing record with the same details, and if such a record exists, to update it.
I was getting that exception when it tried to save these changes.
The solution was to split it up, save the new/updated record first...
// Avoid an "A DataTable named 'Users' already belongs to this DataSet." exception
await _context.SaveChangesAsync();
... and then check for an existing record, update it if necessary, and then doing a separate save...
await _context.SaveChangesAsync();
Yup, it's weird, but saving twice fixed this issue for me.
(I appreciate that this doesn't answer this exact StackOverflow question, but for anyone stumbling onto this page when they hit this strangely-worded exception, this'll be a lifesaver !)
I received this error when running command.ExecuteDataSet on a stored procedure where I declared a table variable then queried that table multiple times to return several datatables in the dataset. Because each datatable was queried from the same table, they all had the same name '#t'. I was able to resolve it by creating multiple table variables with different names in the stored procedure.

.Net Simple Data File usage

I've created a new project in .Net (2010 4.0) and added an SDF data file. I've generated a dataset and created a table in it (and I believe generated the Fill and other methods).
In code, I'm trying to add a row to the database.
eBureauScrubber.App_Data.matchingtempDataSet ds = new App_Data.matchingtempDataSet();
eBureauScrubber.App_Data.matchingtempDataSet.ctfFileRow row = ds.ctfFile.NewctfFileRow();
row.Address = "123 Main St.";
row.City = "Overland Park";
row.FirstName = "Matt";
row.LastName = "Dawdy";
row.rownum = 1;
EDIT: Added the next bit of code.
ds.ctfFile.Rows.Add(row);
ds.ctfFile.AcceptChanges();
ds.AcceptChanges();
eBureauScrubber.App_Data.matchingtempDataSetTableAdapters.ctfFileTableAdapter ctfa = new App_Data.matchingtempDataSetTableAdapters.ctfFileTableAdapter();
ctfa.Update(ds.ctfFile);
This runs fine. However, after the program completes, the data is not persisted in the database. What am I missing?
EDIT: I've tried all different combinations of AcceptChanges() on the datatable, the dataset, running update() before, after, etc. I'm missing something huge here. I'm not even sure it is connecting to the "right" database. Maybe that's my problem.
EDIT 2: Here's what I did to get this to work (it's still funky, though).
Change the properties of my DB file in App_Data to "Do Not Copy"
Manually copy that db file to bin\debug\app_data
Use the data adapter's fill method to fill the ds.ctfFile data table.
Create a row (.NewctfFileRow())
Set values on that row.
ds.ctfFile.Rows.Add(row)
ds.ctfFile.AcceptChanges();
ds.AcceptChanges();
Call the adapater's update method.
Now, the data is in my database file (in bin\debug\app_data), but I can't see it because the Data Sources connection. I'm still trying to find out how to do that.
It should have generated a TableAdapter class with a .Update() method that you have to call to save data in your database. See MSDN for some examples.

Categories