How can i export gridview into MS Access(.mdb) in C# - c#

My question is how can i export gridview into MS Access in C#
for this I am Using the following code:
String accessConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\...\\test.accdb;";
String sqlConnectionString = ConfigurationManager.ConnectionStrings["College"].ConnectionString;
//Make adapters for each table we want to export
SqlDataAdapter adapter1 = new SqlDataAdapter();
// SqlDataAdapter adapter2 = new SqlDataAdapter();
DataTable dtFillGrid = (DataTable)ViewState["FillGrid"];
//Fills the data set with data from the SQL database
// DataSet dataSet = new DataSet();
adapter1.Fill(dtFillGrid);
// adapter2.Fill(dataSet, "Table2");
//Create an empty Access file that we will fill with data from the data set
ADOX.Catalog catalog = new ADOX.Catalog();
catalog.Create(accessConnectionString);
//Create an Access connection and a command that we'll use
OleDbConnection accessConnection = new OleDbConnection(accessConnectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = accessConnection;
command.CommandType = CommandType.Text;
accessConnection.Open();
//This loop creates the structure of the database
foreach (DataTable table in dtFillGrid.Rows)
{
String columnsCommandText = "(";
foreach (DataColumn column in table.Columns)
{
String columnName = column.ColumnName;
String dataTypeName = column.DataType.Name;
String sqlDataTypeName = getSqlDataTypeName(dataTypeName);
columnsCommandText += "[" + columnName + "] " + sqlDataTypeName + ",";
}
columnsCommandText = columnsCommandText.Remove(columnsCommandText.Length - 1);
columnsCommandText += ")";
command.CommandText = "CREATE TABLE " + table.TableName + columnsCommandText;
command.ExecuteNonQuery();
}
//This loop fills the database with all information
foreach (DataTable table in dtFillGrid.Rows)
{
foreach (DataRow row in table.Rows)
{
String commandText = "INSERT INTO " + table.TableName + " VALUES (";
foreach (var item in row.ItemArray)
{
commandText += "'" + item.ToString() + "',";
}
commandText = commandText.Remove(commandText.Length - 1);
commandText += ")";
command.CommandText = commandText;
command.ExecuteNonQuery();
}
}
accessConnection.Close();
but in this code I get an error:
The Type or Namespace name ADOX could not be found

According to accessConnectionString content you should install "Data Connectivity Components" in your machine.
It is available to download at http://www.microsoft.com/en-us/download/details.aspx?id=23734

You need to add a reference for Microsoft ADO Ext. 2.7 for DDL and Security(the version number may be different though) which can be found under the COM section of the references dialog , and then add using ADOX; in your code.

Here I did not export gridview in MS Access but I made a database in MS Access using C# with the help of this code
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
//Create the table and it's fields.
table.Name = "Table1";
table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6]
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger, 10); // Integer
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=d:/m2.accdb;" + "Jet OLEDB:Engine Type=5");
cat.Tables.Append(table);
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" + "Data Source=d:/m2.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Table1([PartNumber],[AnInteger]) VALUES (#FirstName,#LastName)";
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = "neha";
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = 20;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
result = false;
}
cat = null;

Related

Inserting records to MSAccess

Can someone explain to me why it wont allow me to insert my record into MS Access?
for some reason i have tried everything that is humanly possible but it wont let me do what i need to do. what i need to do is allow record to be written from my c Sharp program and would want to press a button which will insert the value into my MS Access.
void Insert_Record(object s, EventArgs e)
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source =BookCSharp.accdb";
string dbcommand = "INSERT INTO BookKey, Title, Pages from Books;";
OleDbConnection conn = new OleDbConnection(dbconnection);
OleDbCommand comm = new OleDbCommand(dbcommand, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
conn.Open();
adapter.Fill(ds, "Books");
conn.Close();
DataTable dt = ds.Tables[0];
//define a new record and place it into a new DataRow
DataRow newRow = dt. NewRow();
newRow["BookKey"] = txtBookKey.Text;
newRow["Title"] = txtTitle.Text;
newRow["Pages"] = txtPages.Text;
//add the new DataRow to DataTable
dt.Rows.Add(newRow);
//update DB
adapter.Update(ds, "Books");
//accept changes
ds.AcceptChanges();
//update listBox1
lstDisplayBooks.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
lstDisplayBooks.Items.Add(row["BookKey"] + " " + row["Title"] + " (" + row["Pages"] + ")");
}
txtBookKey.Enabled = false;
txtBookKey.Text = " ";
txtTitle.Enabled = false;
txtTitle.Text = " ";
txtPages.Enabled = false;
txtPages.Text = " ";
btnInsert.Enabled = false;
}
An OleDbDataAdapter need a SELECT query and an OleDBCommandBuilder to generate automatically the INSERT/UPDATE/DELETE commands that will be used in the Update method
void Insert_Record(object s, EventArgs e)
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source =BookCSharp.accdb";
string dbcommand = "SELECT * FROM Books;";
using(OleDbConnection conn = new OleDbConnection(dbconnection))
using(OleDbCommand comm = new OleDbCommand(dbcommand, conn))
{
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
// See comments below for these properties
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
conn.Open();
adapter.Fill(ds, "Books");
DataTable dt = ds.Tables[0];
DataRow newRow = dt. NewRow();
newRow["BookKey"] = txtBookKey.Text;
newRow["Title"] = txtTitle.Text;
newRow["Pages"] = txtPages.Text;
dt.Rows.Add(newRow);
builder.GetInsertCommand();
adapter.Update(ds, "Books");
}
//update listBox1
lstDisplayBooks.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
lstDisplayBooks.Items.Add(row["BookKey"] + " " + row["Title"] + " (" + row["Pages"] + ")");
}
txtBookKey.Enabled = false;
txtBookKey.Text = " ";
txtTitle.Enabled = false;
txtTitle.Text = " ";
txtPages.Enabled = false;
txtPages.Text = " ";
btnInsert.Enabled = false;
}
The example in the link for the OleDbCommandBuilder contains an example like this.
The code should fix your initial error, but really there is no need to use an OleDbDataAdapter in this scenario. If your only objective is just to add a new record to the datatable and you don't need to maintain a local datasource like a DataGridView it is a lot simpler to use directly the OleDbCommand with an appropriate written INSERT and parameterized query
void Insert_Record(object s, EventArgs e)
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source =BookCSharp.accdb";
string dbcommand = "INSERT INTO Books (BookKey, Title, Pages) VALUES(?,?,?);";
using(OleDbConnection conn = new OleDbConnection(dbconnection))
using(OleDbCommand comm = new OleDbCommand(dbcommand, conn))
{
conn.Open();
comm.Parameters.AddWithValue("#p1", txtBookKey.Text);
comm.Parameters.AddWithValue("#p2", txtTitle.Text);
comm.Parameters.AddWithValue("#p3", txtPages.Text);
comm.ExecuteNonQuery();
}
.....

Getting unknown data from SQL Server using SqlDataReader

I use this code for getting data from SQL Server:
string rootname = "[" + nameroot + "]";
string retVal = "";
string constring = "Data Source =(Local);Initial Catalog=Tajari;Integrated Security=True;";
SqlConnection conobj = new SqlConnection(constring);
string commandtext = "select distinct " + rootname + " from TBLJobsRootName where MenuId between 1 and " + countroot + "";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
//retVal = dr[nameroot].ToString();
}
conobj.Close();
Now I need this data inserted into a variable or textbox.
The problem is that my values are unknown
Solution 1 :
You can use Index value.
Try This:
while (dr.Read())
{
retVal = dr[0].ToString();
}
Solution 2 :
You can also use alias name.
string commandtext = "select distinct " + rootname + " as myrootname from
TBLJobsRootName where MenuId between 1 and " + countroot + "";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
retVal = dr["myrootname"].ToString();
}
Suggestion: Your Query is open to SQL Injection Attacks i would suggest you to use Parameterised Queries to avoid them.
Solution 3: Using Parameterised Queries
if you want to add all rootname values you need to add all values to List.
List<string> list = new List<string>();
string commandtext = "select distinct "+rootname+" as myrootname from
TBLJobsRootName where MenuId between 1 and #countroot";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
comobj.Parameters.AddWithValue("#countroot",countroot);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
lis.Add(dr["myrootname"].ToString());
}
//You can retunrn list

How can I export GridView to MS Access in C#

I want to export grid to MS Access in C#
Here's the code that I've tried:
String accessConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\\...\\test.accdb;";
String sqlConnectionString = ConfigurationManager.ConnectionStrings["College"].ConnectionString;
SqlDataAdapter adapter1 = new SqlDataAdapter();
adapter1.Fill(dtFillGrid);
ADOX.Catalog catalog = new ADOX.Catalog();
catalog.Create(accessConnectionString);
OleDbConnection accessConnection = new OleDbConnection(accessConnectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = accessConnection;
command.CommandType = CommandType.Text;
accessConnection.Open();
foreach (DataTable table in dtFillGrid.Rows) {
String columnsCommandText = "(";
foreach (DataColumn column in table.Columns) {
String columnName = column.ColumnName;
String dataTypeName = column.DataType.Name;
String sqlDataTypeName = getSqlDataTypeName(dataTypeName);
columnsCommandText += "[" + columnName + "] " + sqlDataTypeName + ",";
}
columnsCommandText = columnsCommandText.Remove(columnsCommandText.Length - 1);
columnsCommandText += ")";
command.CommandText = "CREATE TABLE " + table.TableName + columnsCommandText;
command.ExecuteNonQuery();
}
//This loop fills the database with all information
foreach (DataTable table in dtFillGrid.Rows) {
foreach (DataRow row in table.Rows) {
String commandText = "INSERT INTO " + table.TableName + " VALUES (";
foreach (var item in row.ItemArray) {
commandText += "'" + item.ToString() + "',";
}
commandText = commandText.Remove(commandText.Length - 1);
commandText += ")";
command.CommandText = commandText; command.ExecuteNonQuery();
}
}
accessConnection.Close();
How can I do this?
I would suggest you create the MDB database, create the table(s) you want using sql, then at runtime bind the gridview, or loop through the results and do a batch import.
See here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms677200(v=vs.85).aspx
using ADOX; // add a COM reference to "Microsoft ADO Ext. x.x for DDL and Security"
static void CreateMdb(string fileNameWithPath)
{
ADOX.Catalog cat = new ADOX.Catalog();
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5";
cat.Create(String.Format(connstr, fileNameWithPath));
cat = null;
}
if you dont have problem with payement you can use 'Spire doc' to save datagrid into msAccess like so :
private void btnExportToAccess_Click(object sender, EventArgs e)
{
Spire.DataExport.Access.AccessExport accessExport = new
Spire.DataExport.Access.AccessExport();
accessExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
accessExport.DataTable = this.dataGridView1.DataSource as DataTable;
accessExport.DatabaseName = #"..\..\ToMdb.mdb";
accessExport.TableName = "ExportFromDatatable";
accessExport.SaveToFile();
}
and Here a link where you can find more clarification
Here I am not export gridview in MS Access but I made a database in MS Access by using C# with the help of this code:
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
//Create the table and it's fields.
table.Name = "Table1";
table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6]
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger, 10); // Integer
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=d:/m2.accdb;" + "Jet OLEDB:Engine Type=5");
cat.Tables.Append(table);
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" + "Data Source=d:/m2.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Table1([PartNumber],[AnInteger]) VALUES (#FirstName,#LastName)";
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = "neha";
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = 20;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
result = false;
}
cat = null;
Yes I tell you to all of you that we don't need to export data by gridview to MS Access , we can do this directly create database in MS Access using C#

insert data in sqlite using dataset in c#

I have one excel sheet from which I am getting data in dataset using OleDbConnection
private static DataSet ImportExcel(string FileName, bool hasHeaders)
{
string HDR = hasHeaders ? "Yes" : "No";
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName +
";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1\"";
DataSet output = new DataSet();
using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow row in dt.Rows)
{
string sheet = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
cmd.CommandType = CommandType.Text;
DataTable outputTable = new DataTable(sheet);
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
}
}
return output;
}
Now I want to Insert data from this dataset to sqlite table.
This is how we can do it
SQLiteConnection m_dbConnection;
void createDbAndTable()
{
SQLiteConnection.CreateFile("MyDatabase.sqlite");
m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite; Version=3;");
m_dbConnection.Open();
string sql = "create table myValues (name varchar(20), highScore int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
void fillTable(DataSet ds)
{
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var name = dr["name"].ToString();
var score = Convert.ToInt32(dr["value"].ToString());
string sql = "insert into myValues (name, highScore) values ( '" + name + "'," + score + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();
}

How duplicate entries be prevented while using SqlBulkCopy?

I am importing excel data into sql server using SqlbulkCopy, but the problem is i want to prevent any duplicate records being entered. Is there a way by which duplicate can be ignored or deleted automatically?
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
var command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=ARBAAZ-1B14C081;Initial Catalog=abc;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch
{
}
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("excelid", "id");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("exceldata", "data");
bulkCopy.ColumnMappings.Add(mapping1);
bulkCopy.ColumnMappings.Add(mapping2);
bulkCopy.WriteToServer(dr);
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable";
r = "";
SqlCommand cmd = new SqlCommand(s, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch
{
}
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
}
Can this problem be fixed by creating a trigger to delete duplicates? if yes how? i am a newbie i have never created a trigger.
Another problem is no matter what i try i am unable to get column mapping to work. I am unable to upload data when column names in excel sheet and database are different.
You can create INDEX
CREATE UNIQUE INDEX MyIndex ON ExcelTable(id, data) WITH IGNORE_DUP_KEY
And when you will insert data with bulk to db, all duplicate values will not inserted.
no, either you manage it on your dr object on you code before you load it into the db (like running a DISTINCT operation) or you create a trigger on the DB to check. The trigger will reduce the bulk insert's performace though.
Another option would be to bulk insert into a temp table and then insert into your destination table FROM your temp table using a select DISTINCT
as far as I remember,
you could filter out the redundant rows when importing from the excel file itself.
the following SQL query should be used in the OleDbCommand constructor.
var command = new OleDbCommand("Select DISTINCT ID,Data FROM [Sheet1$]", connection);

Categories

Resources