NullReferenceException after accessing datatable added to dataset - c#

So basically, I have a dataset which contains several datatables, from which columns are removed in my program.
At some point I want to reset my datatable so that all changes to the columns are gone.
Because I can't just create a new instance of that datatable in my dataset, I do this:
this._dsTest = new DsTest();
//Removing/Adding the first datatable
this._dsTest.Tables.Remove(this._dsTest.TestTable);
this._dsTest.Tables.Add(new DsTest.TestTableDataTable());
//Removing/Adding the second datatable
this._dsTest.Tables.Remove(this._dsTest.ReloadTable);
this._dsTest.Tables.Add(new DsTest.ReloadTableDataTable());
However, if I try to access the second datatable, I receive a NullReferenceException, telling me that the second dataTable is null.
What I don't understand is:
If I would add another table to my dataset, that third table would throw the NullReferenceException once I try to access it, and the second one would work without any problems.
Is there anything I am missing that would explain this behaviour?
Update:
This is the code I am using to access the datatables:
this._dsTest.TestTable.AddTestTableRow("Test", 1);
this._dsTest.ReloadTable.AddReloadTableRow(1, "Reload", 1); //This throws the exception

When you made any changes to your dataset / datatable you should use AcceptChanges method.
For example :
this._dsTest = new DsTest();
//Removing/Adding the first datatable
this._dsTest.Tables.Remove(this._dsTest.TestTable);
this._dsTest.AcceptChanges();
this._dsTest.Tables.Add(new DsTest.TestTableDataTable());
this._dsTest.AcceptChanges();

So, I finally found the answer to my problem.
The reason that I received the NullReferenceException when I tried to do
this._dsTest.ReloadTable.AddReloadTableRow(1, "Reload", 1)
was, that the datatable that I added to the dataset was working perfectly fine, but the public property of that datatable (this._dsTest.ReloadTable)
was not set to the datatable I had juts added.
So the solution for this is to simply do this:
this._dsTest.InitVars();
After that, accessing the DataTable works without a problem.
Thanks to anyone who tried to help me with this.

Related

DataTable TableName = DataView.ToTable("TableName") will not work

I am trying to make a copy of a DataTable with a different TableName. I have used this in the past without issue and the code from the past works just fine today. When i try using the exact same code the table will add to the DataSet but there is no data or column names.
DataView dv = dataSet.Tables["Traveler"].DefaultView; /// the dataview is exactly like the datatable
DataTable Parts_Kit = dv.ToTable("Parts_Kit"); /// the new datatable has no data or columns
dataSet.Tables.Add("Parts_Kit"); /// Parts_Kit is added to dataset but completly blank
I have dorked around with this for 4 hours now with no results. What could i possibly be missing?
as per the definition of Add(string DataTable name), you are creating a new / blank table in dataSet that has nothing to do with the DataTable Parts_Kit.
As per MS documentation as well, you want to use,
dataSet.Tables.Add(Parts_Kit); // without quotes around Parts_Kit.
This will add the table you created from view (Parts_Kit) to the DataTableCollection, dataSet. To Test this as well, you can print Parts_Kit.TableName to see if it is the correct "Parts_Kit" name (from ToTable("Parts_Kit") command).

Why does CopyToDataTable unsort the DataRow Array

I've got a datatable that I need to sort and place back into another datatable. On the face of this its easy as below:
DataTable sortme = getdata();
sortme.Select("col1 = 'something'", "sortbyme ASC").CopytoDataTable();
However, I've found as soon as I pass the DataRow array created by select() to CopytoDataTable(), the new datatable is no longer sorted by sortbyme.
How do I fix this without creating a loop to push each DataRow into a datatable? And what is causing the sorting to be lost?
There is already a question asked and solved about how to sort DataTables by row, please look at it here, it might help you:
Sorting rows in a data table

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.

c# unable to edit datarow in dataset

I'm trying to edit the data in a dataset (change the value in a column on one row), which is not linked to a database. I've been googling for about an hour with no results and no good examples out there. Hopefully someone can help me.
My table (DataTable1) has these columns - ThreadID (string, PK), StatusText (string).
I can select a row in a DataGridView, and get the ThreadID value. No matter how I've tried to edit the row in the associated dataset, either nothing happens or I get an error. Here's what I have now:
string sThreadID = "";
sThreadID = gridThreads.Rows[gridThreads.CurrentRow.Index].Cells["ID"].Value.ToString(); // gives me a good id, which is in the dataset
DataRow drRow = dataThreads.Tables["DataTable1"].Rows.Find(sThreadID);
drRow["StatusText"] = "Test";
The error I get when getting the row (3rd line) is: "Object reference not set to an instance of an object.". I can't create a new DataRow object because there's no public constructor for it (according to my research).
I'm sure I'm missing something basic, but I'm not familiar with working with datasets. What am I doing wrong? Thanks for your help.
How does drRow know what "statusText" is? You may be only getting a shalllow copy, try cloning/copy so that the data types of the row get copied as well. Just an idea.
Does it happen that dataThreads or Tables["DataTable1"] is null ?
To create a new row, use the NewRow() method of the data table.

SQLiteDataAdapter does not fill the specified DataTable

I'm attempting to pull some data from a SQLite database so that I can populate a GridView in my GUI: here is the code that returns the DataTable:
DataTable table = new DataTable();
SQLiteDataAdapter adapter = new SQLiteDataAdapter(this.command.CommandText, this.connection);
adapter.Fill(table);
return table;
For some reason after calling adapter.Fill, the DataTable is still not populated with anything. So far I've verified that the command text is correct and that the connection contains the correct connection string. Both are used successfully in other parts of the application. No exceptions seem to be thrown... Is there any place else I should be looking for trouble? Am I using the API incorrectly?
Thanks!
This looks like correct usage.
One thing to check -- after the fill you say the datatable is not populated. Were you just checking Rows.Count? What about columns? If the Fill creates columns to match your SELECT statement, but there aren't any rows, then you know the code is working but there's a problem with either your query, or you're not hitting the same database you think you are.
Is there a constructor that lets you just pass in the command directly?

Categories