So I’ve got a control that has all different user inputs (comboBox, textBox, DatePicker, etc.). What I would like is to update a database table “Receipts” with a new row each time the ‘Save’ or ‘Save & Close’ button is clicked.
For each object, I have a data binding to the source. This isn’t throwing any syntactical errors, but that obviously doesn’t mean its right. Here is an example:
this.textBox2.Location = new System.Drawing.Point(73, 150);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(198, 20);
this.textBox2.TabIndex = 15;
this.textBox2.DataBindings.Add("text", ds, "Receipt.Store");
To be fair, I googled how to add a data binding, so that may not even be correct.
For my button, I have the following code, which didn’t work (I’ve got an instance of my DB open as I code, so I can verify):
private void button3_Click(object sender, EventArgs e)
{
SqlCommand saveCommand = new SqlCommand("INSERT INTO Receipt (DateCleared, CategoryID, Amount, Store, DateEntered, HaveReceipt) VALUES (@DateCleared, @CategoryID, @Amount, @Store, @DateEntered, @HaveReceipt)");
saveCommand.Parameters.AddWithValue("@ComboBox", comboBox1.SelectedValue);
saveCommand.Parameters.Add("@Amount", textBox1.Text);
saveCommand.Parameters.Add("@DateCleared", dateTimePicker1);
saveCommand.Parameters.Add("@DateEntered", dateTimePicker2);
saveCommand.Parameters.Add("@Store", textBox2);
saveCommand.Parameters.Add("@HaveReceipt", checkBox1);
this.Dispose();
}
Is this the correct way to go about it? What I am essentially trying to do here is add each value every time the button is clicked; however I fear that this will merely add null values to the rest of the row and create 6 rows each time.
If I need to add code or information let me know. Thanks in advance!
Now this is a stab in the dark, because frankly you didn’t post enough info to adequately answer your question in its current form. Ideally it would be nice to have the database schema, but I think I can guess what the types need to be.
You’re shoving controls (the actual GUI widget) into most of your values. This simply won’t work, the underlying database code has no knowledge of what to do with an object like that. You have to give it the type of data that it’s expecting (varchar fields get strings, datetime fields get DateTime objects, etc). Here’s something that might be closer:
Obviously with the number of assumptions I’m making, your mileage may vary.
EDIT
By the way, you do actually have to execute the SQL when you’re done building it. This just builds the SQL.