user
user

Reputation: 75

Insert Query for Dynamically created textboxes

I have dynamically generated text-box for which i need to write an insert query into my SQL server 2005 database. The problem is when i write the insert query i can't include the text-box names as the text-box will be generated run time.

I tried using the following logic:

PLEASE NOTE THAT I WISH TO GENERATE DYNAMIC TEXTBOXES AND THEN A DYNAMIC SQL QUERY.

   String str=//will contain a data fetched from all the textboxes generated dynamically and will be seprated using a ','(as in an insert statement).

This string str will be directly passed on to the insert query so that all the values will be taken in directly.

But the logic does not work.

Please help..

Upvotes: 0

Views: 1003

Answers (2)

kschieck
kschieck

Reputation: 1447

You need to keep track of your text boxes as they are generated.

List<TextBox> TextBoxes = new List<TextBox>();

...

TextBox DynamicBox1 = new TextBox();
...
TextBoxes.Add(DynamicBox1);

Then if you have the names of your columns somewhere

string Columns = "@col0, @col1, @col2"; //etc

string Query = @"INSERT INTO [Table]
                 (" + Columns.Replace("@", "") + ")
                 VALUES (" + Columns+ ")";

using a paramaterized command

SqlCommand Command = new SqlCommand(Query, Connection);

for (int i=0; i<TextBoxes.Count; i++)
{
    Command.Parameters.AddWithValue("@col" + i, TextBoxes[i].Text);
}

Connection.Open()
Command.ExecuteNonQuery();
Connection.Close()

I have not added in error handling

Upvotes: 0

Binary Worrier
Binary Worrier

Reputation: 51719

A couple of points

  1. Your method leaves you open to SQL injection attacks. This is a bad thing. You should use a sqlCommand object to execute the SQL, using parameter objects to pass in the values to insert, this will guard against SQL Injection attacks.
  2. Name your textboxes after each column in the table your inserting into.

Hope this helps

Upvotes: 1

Related Questions