C# .NET - Create sql table from asp.net - Asked By Dom Afonso on 17-Jun-12 01:52 PM

How to create a sql table from asp.net?
iHelper MS replied to Dom Afonso on 17-Jun-12 02:33 PM
Here is an example:

http://alperguc.blogspot.in/2008/11/c-and-aspnet-create-table-dynamically.html

Hope this helps
kalpana aparnathi replied to Dom Afonso on 17-Jun-12 02:37 PM
hi,

Try with this :

function createtable()
{

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();

}

Regards,
dipa ahuja replied to Dom Afonso on 17-Jun-12 05:13 PM
protected void Button1_Click(object sender, EventArgs e)
{
  string conn = "ConnectionString";
  SqlConnection sqlcon = new SqlConnection(conn);
  sqlcon.Open();
  string query = "Write your create table query";
  SqlCommand comm = new SqlCommand(query, sqlcon);
  comm.ExecuteNonQuery();
}
aneesa replied to Dom Afonso on 18-Jun-12 12:15 AM
In C# use a string builder to concatenate the query and then execute the query.
 
 
    StringBuilder query = new StringBuilder();
    query.Append("CREATE TABLE ");
    query.Append(tableName);
    query.Append(" ( ");
 
 
    for (int i = 0; i < columnNames.Length; i++)
    {
      query.Append(columnNames[i]);
      query.Append(" ");
      query.Append(columnTypes[i]);
      query.Append(", ");
    }
 
 
    if (columnNames.Length > 1) { query.Length -= 2; }  //Remove trailing ", "
    query.Append(")");
    SqlCommand sqlQuery = new SqlCommand(query.ToString(), sqlConn);
    SqlDataReader reader = sqlQuery.ExecuteReader();
Lalit M replied to Dom Afonso on 18-Jun-12 12:56 AM
protected void Button1_Click(object sender, EventArgs e)
    {
      int rows = Convert.ToInt16(TextBox1.Text);
      int cols = Convert.ToInt16(TextBox2.Text);
 
      for (int j = 0; j < rows; j++)
      {
        TableRow r = new TableRow();
        for (int i = 0; i < cols; i++)
        {
          TableCell c = new TableCell();
          c.Controls.Add(new LiteralControl("row" + j.ToString() + ", cell " + i.ToString()));
          r.Cells.Add(c);
        }
        Table1.Rows.Add(r);
      }
    }