title: Create Microsoft Access Table from Windows DataGridView DataTable C#
body: <p>I would like to know how I can create new Microsoft Access Table from Windows DataGridView DataTable in C#.</p>
  
  <ul>
  <li>I already have Database. (E.g. Database.mdb or .accdb)</li>
  <li>But I haven't created tables in my Database file.</li>
  <li>I already have DataGridView which displays the data in table.</li>
  <li>I want to create a new table which is exactly the same as what DataGridView displays.</li>
  </ul>
  
  <p>Please help me solve this problem.
  I've tried creating empty table. But most of my Database Statements are hard-coded. (E.g. I make all my columns VARCHAR datatypes.)
  I am really appreciated.</p>
  
  <p>Thank you so much. :)</p>
  
  <p>These are my codes.</p>
  
  <pre><code>public void CreateDatabaseTable(string database, string dbTableName)
      {
          OleDbConnection con;
          OleDbCommand cmd;
          string queryStr = "";
  
          try
          {
              con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + database);
  
              con.Open();
  
              queryStr = getDataGridViewHeaders().ToString();
  
              cmd = new OleDbCommand("CREATE TABLE " + dbTableName +
                  "( [keyID] AUTOINCREMENT PRIMARY KEY NOT NULL," + queryStr + ")", con);
  
              cmd.ExecuteNonQuery();
  
              con.Close();
          }
          catch (Exception ex)
          {
              MessageBox.Show(ex.ToString());
          }
      }
  
  public string getDataGridViewHeaders()
      {
          int colCount = dataGridView.Columns.Count;
          string headerCols = "";
  
          if (colCount &gt; 0)
          {
              headerCols = "[" + dataGridView.Columns[0].HeaderText + "]" + " VARCHAR";
          }
  
          for (int col = 1; col &lt; colCount; col++)
          {
              headerCols = headerCols + " , " + "[" + dataGridView.Columns[col].HeaderText + "]" + "VARCHAR";
          }
  
          Console.WriteLine(headerCols);
          return headerCols;
      }
  </code></pre>