Column added to .net DataTable does not get added to database Table - c#

I'm new to this site and I started some time ago to program an application.
Right now I'm stuck at a problem and I have no idea how to solve it.
My problem is: I want to register every user in a new column, because I have to save a great amount of data for each of them (up to 1000 rows). Now I add a new column to the already existing table. But the thing is, if I want to retrieve this data I get an error that says there is no column called like this.
programDataSet.User.Columns.Add(textBoxUser.Text, typeof(Int32));
for (int i = 0; i < 4 && i < alchemieDataSet.User.Count; i++)
{
programDataSet.User[i][textBoxUser.Text] = "1";
}
for (int i = 0; i < programDataSet.User.Count; i++)
{
alchemieDataSet.User[i][textBoxUser.Text] = "0";
}
this.Validate();
this.userBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.programDataSet);
MessageBox.Show("Registration completed");
Does anyone have an idea what I made wrong?

I agree with everyone that there are big red flags with data architecture.
But to your specific question, DataSets and Adapters do not change table columns in a target database. They only change rows.
You have to update the columns separately.

Related

Adding Array to Existing DataTable

I have a DataTable, dtHOURS, that consists of two columns of data passed from an SQL database and I am trying to include a third column that consists of calculated values within the array, hours. I've looked at many similar asked questions, but none of the solutions seem to work in my case. I've confirmed that the correct values are being stored in the array, but I can't seem to populate those values within column "Total Hours". All the row data comes out blank for this column.
Any help would be appreciated.
Thank you in advance.
//Create new column and row for the "Total Hours" in data table
DataColumn TotalHoursCol;
DataRow TotalHoursRow;
// Create new DataColumn, set DataType,
// ColumnName and add to DataTable.
TotalHoursCol = new DataColumn();
TotalHoursCol.DataType = System.Type.GetType("System.Double");
TotalHoursCol.ColumnName = "Total Hours";
// Add the Column to the Table.
dtHOURS.Columns.Add(TotalHoursCol);
//This loop calculates the total hours for all jobs and adds them to the data table
for (int i = 1; i < numberOfRecordsHours; i++)
{
//Console.WriteLine(dtHOURS.Rows[i]["ID"]);
//Console.WriteLine(dtHOURS.Rows[i]["ACT_RUN_HRS"]);
if ((Convert.ToString(dtHOURS.Rows[i]["ID"])) == (Convert.ToString(dtHOURS.Rows[i-1]["ID"])))
{
hours[i] = (Convert.ToDouble(dtHOURS.Rows[i]["ACT_RUN_HRS"])) + (hours[i-1]);
//Console.WriteLine(hours[i]);
}
else
{
hours[i] = 0;
//Console.WriteLine("NEW JOB");
}
TotalHoursRow = dtHOURS.NewRow();
TotalHoursRow["Total Hours"] = hours[i];
dtHOURS.Rows.Add(TotalHoursRow);
//Console.WriteLine(dtHOURS.Rows[i]["Total Hours"]);
}
If I am understanding the problem correctly, it looks like you are adding a new row instead of assigning to your new column.
Instead of
TotalHoursRow = dtHOURS.NewRow();
TotalHoursRow["Total Hours"] = hours[i];
dtHOURS.Rows.Add(TotalHoursRow);
Just put
dtHOURS.Rows[i]["Total Hours"] = hours[i];

unreliable information returned

I'm writing an upgrade program for moving Access 2.0 .mdb files to Access 2003 .mdb. We are staying with the mdb file structure for a couple of reasons as this is code that is in several customers locations, and the mdb allows us to utilize existing code.
The main problem:
I go through JET to read in the tables from the file.mdb and read each table into a C# datatable. I then do several checks and duplicate the table in the 2003 mdb db. I use the DataTable.PrimaryKey function to gather the columns that are primary key columns, but I don't get reliable results.
Access 2.0 shows the PrimaryKey in several tables (single column) where DataTable does not, but not always.
I have verified that I do get the PrimaryKey(s) on some tables, just not all.
DataColumn[] dcPrimaryKeyCols = OrgTbl.PrimaryKey;
//Read the Ordinal so we can order the columns correctly
for (int m = 0; m < NumCols; m++)
{
ColumnOrder[m] = OrgTbl.Columns[m].Ordinal;
if (ColumnOrder[m] != m)
MessageBox.Show("In table " + nm+ "out of order ordinal on column: " + OrgTbl.Columns[m].ColumnName);
}
lblStatus.Text = "Creating Table";
pbTableProgress.Value = 0;
pbTableProgress.Maximum = NumCols;
for (int col = 0; col < NumCols;col++ )
{
pbTableProgress.Value = col;
Application.DoEvents();
sColNm=OrgTbl.Columns[col].ColumnName.Trim();
bPrimaryKey = false;
//determine if this column is part of a primary key group
for (int k = 0; k < dcPrimaryKeyCols.Length;k++ )
{
if (dcPrimaryKeyCols[k].ColumnName.Trim().Equals(sColNm))
{
bPrimaryKey = true;
break;
}
}
I have set a breakpoint in the bPrimaryKey = true line, and it gets there sometimes, but not on all the tables where a primarykey is defined.
One thing I noted, in Access Ver 2.0, the column information for the some of the primary keys show: required = no, unique = no. I don't know if this causes JET or the C# datatable to unmark a primarykey column or if other things are at work here. But the end results is that I am not able to correctly detect ALL primarykey columns.

does OnAutoGeneratingColumn e.cancel affect Table.Column.Count?

If I use OnAutoGeneratingColumn to cancel some columns that I don't necessarily want to generate, will it affect the number of columns in Table.Columns.Count?
Context
I'm iterating through a table, row by row, taking each value and passing it through to an insert SQL command. Right now it lines up so that each entry is associated properly. Will I disrupt this with e.cancel? Will row[1] no longer point to what it once did if row[0] was e.cancel'd?
for (int i = 0; i < table.Dummy.Columns.Count; i++)
{
// if we're past our first entry, add room for the next before entering it
if (i != 0)
{
InsertIntoTableQuery.AddIntPrm();
}
//if our column has an entry, add it into our table.
if (row[i] != null)
{
InsertIntoTableQuery.Prms[i].Val = row[i];
}
}
No! I figured out why I was erroring and this wasn't the cause. you can cancel column generation in the wpf datagrid without actually altering the table index's. In hindsight that's pretty obvious.

Insert large amount of data into database using LINQ

I want to insert around 1 million records into a database using Linq in ASP.NET MVC. But when I try the following code it didn't work. It's throwing an OutOfMemoryException. And also it took 3 days in the loop. Can anyone please help me on this???
db.Database.ExecuteSqlCommand("DELETE From [HotelServices]");
DataTable tblRepeatService = new DataTable();
tblRepeatService.Columns.Add("HotelCode",typeof(System.String));
tblRepeatService.Columns.Add("Service",typeof(System.String));
tblRepeatService.Columns.Add("Category",typeof(System.String));
foreach (DataRow row in xmltable.Rows)
{
string[] servicesarr = Regex.Split(row["PAmenities"].ToString(), ";");
for (int a = 0; a < servicesarr.Length; a++)
{
tblRepeatService.Rows.Add(row["HotelCode"].ToString(), servicesarr[a], "PA");
}
String[] servicesarrA = Regex.Split(row["RAmenities"].ToString(), ";");
for (int b = 0; b < servicesarrA.Length; b++)
{
tblRepeatService.Rows.Add(row["hotelcode"].ToString(), servicesarrA[b], "RA");
}
}
HotelAmenties _hotelamenties;
foreach (DataRow hadr in tblRepeatService.Rows)
{
_hotelamenties = new HotelAmenties();
_hotelamenties.Id = Guid.NewGuid();
_hotelamenties.ServiceName = hadr["Service"].ToString();
_hotelamenties.HotelCode = hadr["HotelCode"].ToString();
db.HotelAmenties.Add(_hotelamenties);
}
db.SaveChanges();
tblRepeatService table has around 1 million rows.
Bulk inserts like this are highly inefficient in LINQtoSQL. Every insert creates at least three objects (the DataRow, the HotelAmenities object and the tracking record for it), chewing up memory on objects you don't need.
Given that you already have a DataTable, you can use System.Data.SqlClient.SqlBulkCopy to push the content of the table to a temporary table on the SQL server, then use a single insert statement to load the data into its final destination. This is the fastest way I have found so far to move many thousands of records from memory to SQL.
If performance doesn't matter and this is a 1 shot job you can stick to the way you're using. Your problem is you're only saving at the end, so entity Framework has to store and generate the SQL for 1 million operations at once, modify your code so that you save every 1000 or so inserts instead of only at the end and it should work just fine.
int i = 0;
foreach (DataRow hadr in tblRepeatService.Rows)
{
_hotelamenties = new HotelAmenties();
_hotelamenties.Id = Guid.NewGuid();
_hotelamenties.ServiceName = hadr["Service"].ToString();
_hotelamenties.HotelCode = hadr["HotelCode"].ToString();
db.HotelAmenties.Add(_hotelamenties);
if((i%1000)==0){
db.SaveChanges();
}
i++;
}
db.SaveChanges();

Adding DataRow[] data to each column in an unbound DataGridView?

I am trying to query my DataSet and display the results in an unbound DataGridView. I feel like I am quite close with my programming logic here, but I keep getting the error ArgumentOutOfRange Exception. Index was out of range. Must be non-negative and less than the size of the collection.
My code snippet:
DataRow[] foundRows;
//Queries the Reservations table with the 'searchExpression' variable
foundRows = this.reservationMasterDataSet.Tables["Reservations"].Select(searchExpression);
//If there is at least one record found...
if (foundRows.Length > 0)
{
//Used to count our row indexes
int i = 0;
//Populate the DataGridView with the queried response
foreach (DataRow row in foundRows)
{
//Used to count our column indexes
for (int j = 0; j < reservationMasterDataSet.Tables["Reservations"].Columns.Count; j++)
{
//THIS LINE IS THROWING AN EXCEPTION
dataGridView1.Rows[i].Cells[j].Value = row.ItemArray[j];
}
i++;
}
}
My DataRow contains 12 objects so I made sure that the DataGridView has 12 columns to correspond (and there are 12 in the original database). I think I am getting the exception right away (i is still 0 in debugger). I first tried it using just row[i] but got the same error.
This is meant to be a search results pane, not an editable thing, which is why I want to only return certain results. I figured the DataGridView is the nicest and easiest way to layout the record on a Windows form.
Before you access to DataGridView1.Rows[i].Cells[j], you need to make sure DataGridView1.Rows[i] exists. If no, you need to add it to the DataGridViewRowCollection.
You can find a lot of sample on on this page.

Categories

Resources