Click here to Skip to main content
15,907,497 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
when i click a button in my page, it should create a table in sqlserver 2008,,, how can i do it,,please help me..
Posted
Comments
Babu Kumar 4-Mar-13 4:48am    
Hi Ram,
Whats your exact requirement. Why do u want to create a table at runtime via button click event.
Maciej Los 4-Mar-13 4:58am    
Very good question. My virtual 5!

1 solution

Try putting your table name dynamically. Try this:
C#
string connectionString = ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
string sql = "CREATE TABLE " + txtTableName.Text.Trim() + "(" + "Id int NOT NULL IDENTITY (1,1) PRIMARY KEY," + txtColumn.Text.Trim() + " nvarchar(MAX) NULL";
foreach (Control c in this.Controls)
 {
     if (c.Name.Contains("temp") && c is TextBox)
       {
          if (!String.IsNullOrEmpty(c.Text))
           {
             sql += "," + c.Text.Trim() + " nvarchar(MAX) NULL";
             count++;
            }
       }


 }
sql += ")";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();

View Original Source[^].


--Amit
 
Share this answer
 
Comments
Maciej Los 4-Mar-13 5:07am    
I see ASP.NET tag...
What about permissions to create table on server? Any user can do it?
_Amy 4-Mar-13 5:21am    
Nup. That should be defined before. It's a simple and basic code block which'll create n numbers of SQL tables in database.
Raje_ 4-Mar-13 5:32am    
I don't understand, why would anybody down vote this answer. I mean according to question this solution looks perfect. +5 from my side, Amit.
_Amy 4-Mar-13 5:46am    
Thank you Rajesh. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900