Thursday, December 23, 2010

Inserting Records in Two Lines of Code

After going through some of the logic with binding certain controls on startup, I've finally started playing around with inserting records. Miraculously, I found two lines of code that will essentially add a simple record into a table.
(I'm using Visual Studio 2010, and Microsoft Access.)

I started by creating a little application that will essentially store transaction information. (I hate balancing my checkbook and have been searching for an easy way to keep track of things.)

The 'Accounts' table will essentially store account names and running totals. (Hopefully, if I can get it to work correctly.)
The 'Transactions' table stores basic information inputted via a variety of controls on the form. (I've used combo boxes, and text boxes.)

After researching various ways to add records (I'm very new at this, and was mildly surprised at all the ways you could do it...) I found a very simple way to get the job done.


            String transactionType = comboBox2.Text;
            String acct = comboBox1.Text;
            String nts = textBox1.Text;
            Double amt = Convert.ToDouble(amountTextBox.Text);


            
            MoneyTrackerDataSet1TableAdapters.TransactionsTableAdapter transactionTableAdapter = new...        
                                                          MoneyTrackerDataSet1TableAdapters.TransactionsTableAdapter();
            transactionTableAdapter.Insert(transactionType, amt, acct, nts);


First, I loaded into variables all the information I wanted from the controls, then used a simple built in Insert method to insert a new record. Except for the setup code, it was done quickly and smoothly in two lines.

Now, I wonder, how many issues will crop up? I'm sure to do it all properly, there should be checks and other measures in place before you go adding random stuff into a database.

No comments:

Post a Comment