I have a Visual Studio C# Forms project. In that project is SmartCon.mdf. As you can see below the DataSet is created.
For some reason the data is not saving. When I add a player to the dataset my code is as follows.
SmartConDataSet.PlayersRow newPlayer = myData.Players.NewPlayersRow();
newPlayer.Id = Guid.NewGuid().ToString();
newPlayer.Guid = newGuid;
newPlayer.FirstSeen = DateTime.Now;
newPlayer.Kills = 0;
newPlayer.Deaths = 0;
newPlayer.TotalScore = 0;
myData.Players.AddPlayersRow(newPlayer);
SmartConDataSet.NamesRow newName = myData.Names.NewNamesRow();
newName.Id = Guid.NewGuid().ToString();
newName.Name = Name;
newName.PlayerId = newPlayer.Guid;
newName.Active = 1;
myData.Names.AddNamesRow(newName);
//Update the database
myData.AcceptChanges();
Why isn't my data saving to the database?
UPDATE:
I can confirm the data is getting added to the DataSet, but not transfering to the Database.
UPDATE 2: I may need a connection string to the database????
UPDATE 3:
var playerTableAdapter = new SmartConDataSetTableAdapters.PlayersTableAdapter();
SmartConDataSet.PlayersRow newPlayer = myData.Players.NewPlayersRow();
newPlayer.Id = Guid.NewGuid().ToString();
newPlayer.Guid = newGuid;
newPlayer.FirstSeen = DateTime.Now;
newPlayer.Kills = 0;
newPlayer.Deaths = 0;
newPlayer.TotalScore = 0;
playerTableAdapter.Insert(newPlayer.Guid, newPlayer.Kills, newPlayer.Deaths, newPlayer.Id, newPlayer.FirstSeen, newPlayer.FirstSeen, 0);
//Add the players name to the name table
var namesTableAdapter = new SmartConDataSetTableAdapters.NamesTableAdapter();
SmartConDataSet.NamesRow newName = myData.Names.NewNamesRow();
newName.Id = Guid.NewGuid().ToString();
newName.Name = Name;
newName.PlayerId = newPlayer.Id;
newName.Active = 1;
var result = namesTableAdapter.Insert(newName.Id, newName.PlayerId, newName.Name, 1);
From my research, a DataSet cannot directly make changed to the database. See this thread...
Does instantiating a DataSet object automatically create a connection to a SQL service-based database for CRUD operations?
However my database is still not being updated with the new rows.
UPDATE 4:
According to the link in update 3, the connection string was wrong as well. everything works great, HOWEVER, My connection string is now a path on my computer rather than a relative path. If I place this on someone else computer it wont work as their file path will not be the same as mine.
The database is not updated using these methods. you need to use TableAdapter.Insert Update etc
Related
I need to modify the UpgradeCode property of the Upgrade MSI table via C#.
This code works ok with other tables' properties, but throws an error when I'm trying to modify these.
using (var database = new Database(TEMPDATABASE, DatabaseOpenMode.Direct))
{
string upgradeCode = Guid.NewGuid().ToString("B").ToUpper();
database.Execute("Update `Upgrade` Set `Upgrade`.`UpgradeCode` = '{0}'", upgradeCode);
}
The error is:
Microsoft.Deployment.WindowsInstaller.InstallerException: 'Function failed during execution.'
I got curious and pillaged github.com - and it giveth the following: Full project - just download it as a whole.
The actual code was (some unicode line feed issues in the file on github.com, I have fixed them up here):
public static void UpdateUpgradeTable(this Database db, Guid upgradeCode)
{
using (View view = db.OpenView("SELECT * FROM `Upgrade`", new object[0]))
{
view.Execute();
using (Record record = view.Fetch())
{
record[1] = upgradeCode.ToString("B").ToUpperInvariant();
view.Replace(record);
}
db.Commit();
}
}
I took the above and made the following mock-up (very ugly, but it worked):
using (Database db = new Database(#"C:\Test.msi", DatabaseOpenMode.Direct))
{
using (View view = db.OpenView("SELECT * FROM `Upgrade`", new object[0]))
{
view.Execute();
using (Record record = view.Fetch())
{
record[1] = "{777888DD-1111-1111-1111-222222222222}";
record[2] = "";
record[3] = "4.0.1";
record[4] = "";
record[5] = "1";
record[6] = "";
record[7] = "WIX_UPGRADE_DETECTED";
view.Replace(record);
}
db.Commit();
using (Record record = view.Fetch())
{
record[1] = "{777888DD-1111-1111-1111-222222222222}";
record[2] = "";
record[3] = "";
record[4] = "4.0.1";
record[5] = "1";
record[6] = "";
record[7] = "WIX_DOWNGRADE_DETECTED";
view.Replace(record);
}
db.Commit();
}
}
The SDK doc says:
UPDATE queries only work on nonprimary key columns.
UpgradeCode is the primary key for the Upgrade table.
I programmatically create a credit memo and then i release by ARDocumentRelease.ReleaseDoc(rebateRelease, false); and i got this error.
{"Error: Another process has updated the 'ARRegister' record. Your changes will be lost."}.
The effect of this error is in the journal transaction, the created journal transaction is having a unposted status. Please check the images thanks.
Unposted Journal Transaction, Closed Credit Memo, Error in code, Suggestion 1
MY CODE BELOW:
`ARInvoice arInvoice = new ARInvoice();
arInvoice.DocType = "CRM";
arInvoice.CustomerID = loan.BAccountID;
arInvoice.CustomerLocationID = loan.CustomerLocation;
arInvoice.DocDesc = "";
arInvoice.OpenDoc = true;
arInvoice.Released = false;
arInvoice.Hold = false;
arInvoice.Status = "B";
if (arSetup.RequireControlTotal == true)
{
arInvoice.CuryOrigDocAmt = amount;
}
arInvoice = ARGraph.Document.Update(arInvoice);
ARGraph.Actions.PressSave();
ARTran arTran = new ARTran();
arTran.RefNbr = arInvoice.RefNbr;
arTran.LineNbr = 1;
arTran.SortOrder = 1;
arTran.TranDesc = description;
arTran.AccountID = accountID;
arTran.SubID = subID;
arTran.Qty = 1;
arTran.TaxCategoryID = other.TaxCategoryID;
arTran.CuryExtPrice = amount;
arTran.Released = false;
ARGraph.Transactions.Insert(arTran);
ARGraph.Actions.PressSave();
rebateRelease.Add(arInvoice);
ARDocumentRelease.ReleaseDoc(rebateRelease, false);`
Try to change the last few lines to this...
rebateRelease.Add(ARGraph.Document.Current);
ARDocumentRelease.ReleaseDoc(rebateRelease, false);
My guess your issue is that you saved the graph which updated your arInvoice record and you are still using the old arInvoice record through that object. You need the updated value after you did the press save.
Also to save some overhead you can just save once before you send the doc to release. No need to save after the ARGraph.Document.Update(arInvoice) line.
I need help on how to INSERT, UPDATE and DELETE data using entity-framework. But it is not working.
Give me an example?
my code Edit:
var maso = Request.Cookies["NguoiDung"].Value;
using (CalibraMainEntities dv = new CalibraMainEntities())
{
Device dev = new Device();
dev.KMH = txtKMH.Text;
dev.Name_TB = txtNameTB.Text;
dev.Model = txtModel.Text;
dev.Serial = txtSerial.Text;
dev.Date_Entry = DateTime.Parse(txtNgayVe.Text);
dev.Main_Place = txtMainPlace.Text;
dev.Calibra_Place = txtCalibraPlace.Text;
dev.Location = txtLocation.Text;
dev.Staff_ID = maso;
dev.Workshop = int.Parse(drWorkshop.SelectedValue);
dev.Status = int.Parse(drStatus.SelectedValue);
dev.Ware_ID = int.Parse(drWareHouse.SelectedValue);
dv.Devices.Attach(dev);
dv.Entry(dev).State = EntityState.Modified;
dv.SaveChanges();
}
i'm sorry. i wouldn't post this if i weren't out of ideas. i've tried everything in the forums, but to no avail.
so i have 2 tables. both are empty at the beginning. the first table is kind of like a customer masterlist where the user creates a new customer profile. here is the code:
con.Open();
System.Data.SqlClient.SqlCommandBuilder cb;
System.Data.SqlClient.SqlCommandBuilder readingcb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
readingcb = new System.Data.SqlClient.SqlCommandBuilder(readingda);
DataRow dRow = custMaster.Tables["custMaster"].NewRow();
DataRow readingdRow = reading.Tables["reading"].NewRow();
dRow[1] = a_newCust.Text;
readingdRow[9] = a_newCust.Text;
dRow[2] = b_newCust.Text;
readingdRow[10] = b_newCust.Text;
dRow[3] = c_newCust.Text;
readingdRow[11] = c_newCust.Text;
dRow[4] = d_newCust.Text;
readingdRow[0] = d_newCust.Text;
dRow[5] = e_newCust.Text.ToString();
readingdRow[2] = e_newCust.Text.ToString();
dRow[6] = f_newCust.Text;
readingdRow[1] = f_newCust.Text;
dRow[7] = g_newCust.Text.ToString();
if (radioButton1.Checked == true)
{
dRow[8] = radioButton1.Text;
readingdRow[3] = radioButton1.Text;
}
else if (radioButton2.Checked == true)
{
dRow[8] = radioButton2.Text;
readingdRow[3] = radioButton2.Text;
}
dRow[9] = "Active";
readingdRow[12] = "Active";
readingdRow[4] = 0;
readingdRow[5] = 0;
custMaster.Tables["custMaster"].Rows.Add(dRow);
reading.Tables["reading"].Rows.Add(readingdRow);
MaxRows = MaxRows + 1;
readingMaxRows = readingMaxRows + 1;
inc = MaxRows - 1;
readinginc = readingMaxRows - 1;
this.da.Update(custMaster, "custMaster");
this.readingda.Update(reading, "reading");
da.Fill(masterDataSet3.custMaster);
readingda.Fill(streetDataSet.reading);
masterfileGrid.Invalidate();
readingGrid.Invalidate();
masterfileGrid.Refresh();
readingGrid.Refresh();
MessageBox.Show("Customer succesfully added!");
con.Close();
when this part completes, my program will create a new record in the "custMaster" table, and also a new record in the "reading" table (but this record still has some null fields). when the user goes to the "reading" table, he sees the new record, and then updates that record by adding some column values (thereby filling in the null fields). here is the code:
con.Open();
System.Data.SqlClient.SqlCommandBuilder readingup;
System.Data.SqlClient.SqlCommandBuilder custpayadd;
readingup = new System.Data.SqlClient.SqlCommandBuilder(readingda);
custpayadd = new System.Data.SqlClient.SqlCommandBuilder(custpayda);
int test = int.Parse(f_reading.Text);
int prev = int.Parse(readingNinBox.Text);
DataRow readingdRow = reading.Tables["reading"].Rows[test-1];
readingdRow[4] = prev;
readingdRow[5] = int.Parse(d_reading.Text);
readingdRow[13] = e_reading.Value.ToShortDateString();
readingdRow[6] = int.Parse(d_reading.Text) - prev;
if (g_reading.Text == "Residential")
{
DataRow resSearchdRow = water.Tables["water"].Rows[int.Parse(d_reading.Text) - prev];
readingdRow[7] = resSearchdRow[2];
}
else
{
DataRow commSearchdRow = commWater.Tables["commWater"].Rows[int.Parse(d_reading.Text) - prev];
readingdRow[7] = commSearchdRow[2];
}
this.readingda.Update(reading, "reading"); //>>>>>>>>>>this part is where i get the concurrency error.
readingda.Fill(streetDataSet.reading);
readingGrid.Invalidate();
readingGrid.Refresh();
//elsewhere:
masterDataSet reading;
System.Data.SqlClient.SqlDataAdapter readingda;
int readingMaxRows = 0;
int readinginc = 0;
this.readingTableAdapter.Fill(this.streetDataSet.reading);
reading = new masterDataSet();
string readingsql = "SELECT * From reading";
readingda = new System.Data.SqlClient.SqlDataAdapter(readingsql, con);
readingda.Fill(reading, "reading");
readingMaxRows = reading.Tables["reading"].Rows.Count;
readingda.Update(reading, "reading");
i don't understand why i get this, since i use the same lines of updating codes in my other forms but they work well. any help would be greatly appreciated. thanks.
Some additional information: i only get the error the first time a record is added to the "reading" table. when i close and reopen my program, i can update the record fine.
i have the same problem. but i am using Visual studio 2010 with C# and windows form. i solved my problem by placing "this.contactDBDataSet.AcceptChanges(); before "this.tableAdapterManager.UpdateAll(this.contactDBDataSet);". here is the sample.
private void peopleBindingNavigatorSaveItem_Click_2(object sender, EventArgs e)
{
this.Validate();
this.peopleBindingSource.EndEdit();
this.contactDBDataSet.AcceptChanges();// added by Humayoo
this.tableAdapterManager.UpdateAll(this.contactDBDataSet);
}
this.contactDBDataSet.AcceptChanges();
That Right !! FIN
I received this error message because my workstation was set to a different time zone than my server. Once I got it back to the same time zone...problem went away
This error is mostly because of updating multiple changes to database without reloading updated data between requests and when you try to save(Update) stacked changes this error may occur.
For more info check this answer by Henk which was very helpful for me.
And here there is a good example in details.
I know this thread is old, but I'd like to share the situation in which I got this error in case anyone runs across this also from an internet search.
I was seeing this error message in a legacy app. It turned out to be a result of a previous programmer coding up some logic that retrieved a DataTable, forcibly removed a column from it, then allowed the user to edit the DataTable in a grid. The DataTable was then passed to the adapter (an OracleDataAdapter in my case) to apply any changes.
So...manually removing a column from a DataTable before sending it to the SqlDataAdapter can also result in this error message.
I have the following code:
private void Timer1Tick(object sender, EventArgs e)
{
timer_ScanTimer.Enabled = false;
var psc = new ParseScannedCheckNumbers();
if (psc.ParseCheck(_checkData))
{
label_Status.Text = #"Scan Next Check";
var ct = checkTrans.IndividualCheck.NewIndividualCheckRow();
ct.Date = DateTime.Now.ToShortDateString();
var bracct = GetBranchAccountNumber(psc.BankAccountNumber);
if (bracct.Trim().Length == 7)
{
ct.Branch = bracct.Substring(0, 2);
ct.AccountNumber = bracct.Substring(2, 5);
ct.NameOnCheck = GetAccountName(ct.Branch + ct.AccountNumber);
ct.AccountBalance = GetAccountBalance(ct.Branch + ct.AccountNumber);
}
else
{
ct.Branch = Configuration.Branch;
ct.AccountNumber = string.Empty;
ct.NameOnCheck = string.Empty;
ct.AccountBalance = 0;
}
ct.CheckAmount = 0;
ct.BankRoutingNumber = psc.BankRoutingNumber;
ct.BankAccountNumber = psc.BankAccountNumber;
ct.CheckNumber = psc.CheckNumber;
ct.Status = "Entered";
checkTrans.IndividualCheck.Rows.Add(ct);
}
else
{
label_Status.Text = Resources.ScanCheck_ScanFailed;
}
_checkData = string.Empty;
var rs = new RegistrySettings();
if (!rs.ScanChecksContinuous)
{
StopScanning();
label_Status.Text = Resources.ScanCheck_Success;
EditLastRowEntered();
}
label_ChecksScanned.Text = (dgv_Checks.RowCount - 1).ToString();
}
When the timer goes off, I verified that I have received all of the data, then I add it to the dataset. It's being added to the dataset without issue, it's just being seen on the datagridview every time. Sometimes it works, most time it doesn't.
How do I get the datagridview to update when changes are done to the dataset? Am I doing something wrong in the above code?
Thanks! (again)
If you created the dataset and attached it to the DataGridView using the Visual Studio Data Source Configuration Wizard, then you probably have a call to
this.somethingTableAdapter.Fill(this.yourDataSet.someDataTable);
somewhere in your code. This is what actually loads the data from the DataSet into your DataGridView. While calling this method again might not be the 'proper' way to refresh your DGV, it did the job for me.