Reputation: 75
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
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
Reputation: 51719
A couple of points
Hope this helps
Upvotes: 1