I would like to know how I can create new Microsoft Access Table from Windows DataGridView DataTable in C#.
- I already have Database. (E.g. Database.mdb or .accdb)
- But I haven't created tables in my Database file.
- I already have DataGridView which displays the data in table.
- I want to create a new table which is exactly the same as what DataGridView displays.
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.
Thank you so much. :)
These are my codes.
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 > 0)
{
headerCols = "[" + dataGridView.Columns[0].HeaderText + "]" + " VARCHAR";
}
for (int col = 1; col < colCount; col++)
{
headerCols = headerCols + " , " + "[" + dataGridView.Columns[col].HeaderText + "]" + "VARCHAR";
}
Console.WriteLine(headerCols);
return headerCols;
}