Dataset won't commit to database
I am a DB programming noob. I need to populate a DB from textbox fields but when I try to then commit it to the DB, I go and view the database and all I see is Nulls... nothing is being saved... please help..
thanks
private void btnSubmit_Click(object sender, EventArgs e)
{
TradesDataSet.TradesRow newTradesRow = tradesDataSet.Trades.NewTradesRow();
newTradesRow.ID = textBoxTradeID.Text;
newTradesRow.EntryPrice = textBoxEntryPrice.Text;
newTradesRow.ExitPrice = textBoxExitPrice.Text;
tradesDataSet.Trades.Rows.Add(newTradesRow);
tradesDataSet.Trades.AcceptChanges();
try
{
this.Validate();
this.tradesBindingSource.EndEdit();
this.tradesTableAdapter.Update(this.tradesDataSet.Trades);
MessageBox.Show("Update successful");
}
catch (System.Exception 开发者_开发问答ex)
{
MessageBox.Show("Update failed");
}
}
Remove the AcceptChanges
call. Data adapter's Update
method looks at the changes in the database and uses the change list to update the actual database. It automatically accepts the changes in the DataSet
after the update. If you call AcceptChanges
on the DataSet
manually before updating, the DataAdapter
will think nothing is changed and doesn't do anything.
There is another possibility. If you have added a database to your project and have set its "Copy to Output Directory" property as "Always", any changes you have made to your database will be reverted as the newer copy gets replaced by the old one.
To prevent this set that property to "Copy if newer" or "Don't copy"
See ADO.NET: Update a Database from a DataSet;
private void btnSubmit_Click(object sender, EventArgs e)
{
TradesDataSet.TradesRow newTradesRow = tradesDataSet.Trades.NewTradesRow();
newTradesRow.ID = textBoxTradeID.Text;
newTradesRow.EntryPrice = textBoxEntryPrice.Text;
newTradesRow.ExitPrice = textBoxExitPrice.Text;
tradesDataSet.Trades.Rows.Add(newTradesRow);
//Wrong, this command says that what I have in the dataset is what is in
//the database. You only use this if you manually update the dataset in
//the background.
//tradesDataSet.Trades.AcceptChanges();
try
{
//EndEdit then force a validate.
this.tradesBindingSource.EndEdit();
this.Validate();
//Internally this method calls .AcceptChanges();
this.tradesTableAdapter.Update(this.tradesDataSet.Trades);
MessageBox.Show("Update successful");
}
catch (System.Exception ex)
{
MessageBox.Show("Update failed");
}
}
精彩评论