Monday, May 24, 2010

How do I use the InsertCommand to insert a new record into a database from textboxes? (Using C#)?

I'm trying to add new records to my database using 4 textboxes, one for each field in my databases table. I've got ID, Firstname, Surname and Course.





But I can't figure out at all how to link whats Inputted into the textboxes to be added as a new record to my database when the "Insert Record" button is pushed.., i've spent nearly 2 hours searching the internet for tutorials and people asking similar questions but I can't find anything that works.





I think the solution might be in this line of code:








InsertCommand="INSERT INTO [Data1] ([ID], [Firstname], [Surname], [Course]) VALUES ()"





I've tried putting the ID's of my textboses in the "VALUES ()" part..


[I]


(e.g. VALUES (ID.Text, Firstname.Text, Surname.Text, Course.Text)[/I]





But that doesn't seem to work, I need the values to be what has been inputted into my textboxes, but I'm not sure what the correct way to do that is or what I need to write between the brackets.





My textboxes ID's are ID, Firstname, Surname and Course.

How do I use the InsertCommand to insert a new record into a database from textboxes? (Using C#)?
Boy did you come to the right guy. I've written a dozen books on this subject... ;)





Okay, you're close.


Consider that the INSERT SQL statement has to include the actual values and these have to be in "framing" quotes to deliniate strings. Keeping things simple, you'll need code to make the INSERT statement look like this:





INSERT INTO [Data1] ([ID], [Firstname], [Surname], [Course]) VALUES ('Fred', 'Farkle', 1234)





To get C# to insert the values into the VALUES clause, you should (when using best practices) create a Parameter for each of the values to be passed into the clause. That's a bit advanced so let's take a smaller step.





Let's say the values are in TextBox1, 2 and 3. This means you need to concatenate the strings into the INSERT statement something like this:





InsertCommand="INSERT INTO [Data1] ([ID], [Firstname], [Surname], [Course]) VALUES ('" + TextBox1.Text + "'," TextBox2.Text + "', " + TextBox3.Text + ")"





Note that the first two strings are framed with single quotes ('). Yes, this can lead to a couple of serious issues including SQL injection as well as the O'Malley problem--both of which are discussed in detail in my books.





hth


No comments:

Post a Comment