DataTable.Copy() didnt copy the first row - c#

I tried to copy a datatable using this code :
private void button1_Click(object sender, EventArgs e)
{
DataTable dat = dGV.DataSource as DataTable;
DataTable dt = new DataTable();
dt = dat.Copy();
dGV.DataSource = dt;
}
But when I ran it, the first row wasnt copied. The result looks like this :
Before : https://drive.google.com/file/d/0B--Fi4mWsFk5NXlJM0ZRSXhRbjA/view?usp=sharing
After : https://drive.google.com/file/d/0B--Fi4mWsFk5OFptY2ZPRHlNaWc/view?usp=sharing
If I move the cursor into the second row before clicking the button it will copy all data including the first row. The data was imported from excel using this code :
private void importFileDialog_FileOk(object sender, CancelEventArgs e)
{
dGV.DataSource = GetTable();
string path = importFileDialog.FileName;
string ext = Path.GetExtension(path);
if (ext == ".xlsx" | ext == ".xls")
{
try
{
string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;";
string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0;";
string conStr, sheetName;
conStr = string.Empty;
switch (ext)
{
case ".xls": //Excel 97-03
conStr = string.Format(Excel03ConString, path);
break;
case ".xlsx": //Excel 07
conStr = string.Format(Excel07ConString, path);
break;
}
//Get the name of the First Sheet.
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
con.Close();
}
}
//Read Data from the First Sheet.
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
//Populate DataGridView.
//dGV.DataSource = dt;
for (int i = 0; i < dt.Rows.Count; ++i)
{
//dGV.RowCount++;
//dGV.Rows[i].HeaderCell.Value = dt.Row[i].;
for (int k = 0; k < dt.Columns.Count; ++k)
{
dGV[k, i].Value = dt.Rows[i].ItemArray[k];
}
}
}
}
}
}
catch
{
MessageBox.Show("Failed to read the file");
}
}
}
If I input the data manually everything works fine.

You can also use clone function try this
private void button1_Click(object sender, EventArgs e)
{
DataTable dat = (DataTable)dGV.DataSource;
DataTable dt = new DataTable();
dt = dat.Clone();
dGV.DataSource = dt;
}
or
DataTable dt = (DataTable)dGV.DataSource;
dGV.DataSource = dt;

Related

How can we Validate Column names of Excel sheet with Table values using OLEDB

I want to validate column names of uploaded excel sheet with table definition.
Here i get table definition from database and also i get the column names from excel sheet using OLEDB.
i want to validate where all the column from the table is available in excel columns. Here i get both column names (that is from excel and table (DB)).
Here is the code i tried
//for validating column names
public bool ValidateColumnNames(string filename,DataExchangeDefinition dataExchangeDefinition)
{
string extension = Path.GetExtension(filename);
string connstring = string.Empty;
try
{
switch (extension)
{
case ".xls":
connstring = string.Format(ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString, filename);
break;
case ".xlsx":
connstring = string.Format(ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString, filename);
break;
}
using (OleDbConnection connExcel = new OleDbConnection(connstring))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = connExcel;
connExcel.Open();
var dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
connExcel.Close();
string firstSheet = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
cmd.CommandText = "SELECT top 1 * FROM [" + firstSheet + "]";
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
DataTable HeaderColumns = new DataTable();
da.SelectCommand = cmd;
da.Fill(HeaderColumns);
foreach (DataColumn column in HeaderColumns.Columns)
{
//Here i want to validate the column names
dataExchangeDefinition.FieldName = column.Caption.ToString();
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return true;
}
Here is the answer it works fine for me
//for validating column names
public List<DataExchangeDefinition> ValidateColumnNames(string filename, List<DataExchangeDefinition> dataExchangeDefinitionList)
{
DataExchangeDefinition dt = new DataExchangeDefinition();
//List<DataExchangeDefinition> dataexchangedefinitionList = new List<DataExchangeDefinition>();
string extension = Path.GetExtension(filename);
string connstring = string.Empty;
try
{
switch (extension)
{
case ".xls":
connstring = string.Format(ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString, filename);
break;
case ".xlsx":
connstring = string.Format(ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString, filename);
break;
}
using (OleDbConnection connExcel = new OleDbConnection(connstring))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = connExcel;
connExcel.Open();
var dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); //To get the sheet name
connExcel.Close();
string firstSheet = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
cmd.CommandText = "SELECT top 1 * FROM [" + firstSheet + "]";
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
DataTable HeaderColumns = new DataTable();
da.SelectCommand = cmd;
da.Fill(HeaderColumns);
//List<DataColumn> excelColumn = new List<DataColumn>();
//var excelColumn = new List<DataColumn>();
//foreach (DataColumn column in HeaderColumns.Columns)
//{
// excelColumn.Add(column);
//}
foreach (DataExchangeDefinition data in dataExchangeDefinitionList)
//for(int i=0;i<dataExchangeDefinitionList.Count;i++)
{
dt.IsColumnValid = false;
//var result = from excelColumn in HeaderColumns;
foreach (DataColumn column in HeaderColumns.Columns)
{
if (data.FieldCaption == column.Caption)
{
data.IsColumnValid = true;
break;
}
}
}
return dataExchangeDefinitionList;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
//return isColumnValid;
}
}
}

How do I add a key to the app.config file

I am new to automation and I am trying to get data from an Excel sheet using OLEDB, I get an errror saying "OLEDB Exception : Invalid argument" in C#
So, One of the answers to a similar question suggest that I add a key to the app.config file for my test data. Now I am not familiar with the .config files
So, I need help with the key or any other solutions to my problem will do
Here is my code:
{
class ExcelDataAccess
{
public static string TestDataFileConnection()
{
var fileName =
ConfigurationManager.AppSettings[#"Path\DataSet.xlsx"];
var con = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source = {0}; Extended Properties='Excel 12.0 Xml;HDR=YES;'", fileName);
return con;
}
public static UserData GetTestData(string keyName)
{
using (var connection = new
OleDbConnection(TestDataFileConnection()))
{
connection.Open();
var query = string.Format("select * from [DataSet$] where
key='{0}'", keyName);
var value = connection.Query<UserData>
(query).FirstOrDefault();
connection.Close();
return value;
}
}
I use ExcelDataReader - https://github.com/ExcelDataReader/ExcelDataReader
using ExcelDataReader;
using System.Collections.Generic;
using System.IO;
namespace Test.Data.Excel
{
public class Reader
{
public static IEnumerable<object[]> Read(string filePath)
{
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var count = reader.FieldCount;
do
{
var list = new List<object>();
while (reader.Read())
{
list.Add(reader.GetString(0));
}
yield return list.ToArray();
} while (reader.NextResult());
}
}
}
}
}
Try with the following code to import data from Excel sheet.
"openFileDialog1_FileOk" is a Button
Private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
string filePath = openFileDialog1.FileName;
string extension = Path.GetExtension(filePath);
string header = rbHeaderYes.Checked ? "YES" : "NO";
string conStr, sheetName;
conStr = string.Empty;
switch (extension)
{
case ".xls": //Excel 97-03
conStr = string.Format(Excel03ConString, filePath, header);
break;
case ".xlsx": //Excel 07
conStr = string.Format(Excel07ConString, filePath, header);
break;
}
//Get the name of the First Sheet.
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
con.Close();
}
}
//Read Data from the First Sheet.
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
sampleDatatable = dt;
con.Close();
dataGridView1.DataSource = dt;
//dataGridView2.DataSource = Headers;
}
}
}
}

How to display certain table schema columns in a datagridview control using C#?

I have a method that displays the entire schema of an MS Access table into a datagridview control. How would I be able to display just the column name and data type schema columns in the datagridview. The method that I am working with is below. Thank you for any advice.
private void ButtonFieldHelp_Click(object sender, EventArgs e)
{
char ch = '"';
dbConn = new OleDbConnection();
dbCmd = new OleDbCommand();
DataTable data;
OleDbDataReader reader;
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + this.stringData + ch;
dbConn.Open();
dbCmd.Connection = dbConn;
dbCmd.CommandText = "SELECT * FROM " + this.comboBox.SelectedItem.ToString();
reader = dbCmd.ExecuteReader();
foreach (DataRow tableField in data.Rows)
{
foreach (DataColumn tableProperty in data.Columns)
{
dataGridView.DataSource = data;
}
}
this.txtRecords.Text = data.Rows.Count.ToString();
reader.Close();
dbConn.Close();
}
Here is your code modified to work as you need using OleDbDataAdapter:
private void ButtonFieldHelp_Click(object sender, EventArgs e)
{
char ch = '"';
var dbConn = new OleDbConnection();
var dbCmd = new OleDbCommand();
DataTable data = new DataTable();
OleDbDataReader reader;
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + this.stringData + ch;
dbConn.Open();
dbCmd.Connection = dbConn;
dbCmd.CommandText = "SELECT * FROM " + this.comboBox.SelectedItem.ToString();
//reader = dbCmd.ExecuteReader();
OleDbDataAdapter adapter = new OleDbDataAdapter(dbCmd);
adapter.Fill(data);
var dataTable = new DataTable();
dataTable.Columns.Add("ColumnName");
dataTable.Columns.Add("ColumnType");
foreach (DataColumn column in data.Columns)
{
dataTable.Rows.Add(column.ColumnName, column.DataType.ToString());
}
this.dataGridView1.DataSource = dataTable;
this.txtRecords.Text = data.Rows.Count.ToString();
dbConn.Close();
}

SqlBulkCopy ColumnMappings not working [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Unable to compare the columns in SqlBulkCopy
I have an excel sheet with columns :
excelid | exceldata
1 | cat
2 | bat
3 | rat
My database table:
id (int) | varchar(50)
following is my code:
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;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand 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("id", "id");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "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 !";
}
}
}
}
//protected void Button2_Click(object sender, EventArgs e)
//{
// string fileName = FileUpload1.PostedFile.FileName.ToString();
// Response.Write(fileName);
//}
protected void Button2_Click(object sender, EventArgs e)
{
}
Your excel spreadsheet columns are:
excelid | exceldata
Your db columns are (i'm guessing as you don't actually say):
id | data
Therefore your mappings should be
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("excelid", "id");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("exceldata", "data");

Importing Any Excel Spreadsheet into a DataGridView - C#

I have a program that imports an excel spreadsheet into a datagridview. I have written the code as follows:
try
{
OleDbConnectionStringBuilder connStringBuilder = new OleDbConnectionStringBuilder();
connStringBuilder.DataSource = file;
connStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=NO;IMEX1");
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand selectCommand = factory.CreateCommand();
selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connStringBuilder.ConnectionString;
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
data = new DataSet();
adapter.Fill(data);
dataGridView1.DataSource = data.Tables[0].DefaultView;
}
catch (IOException)
{
}
The line "selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";" takes the data from the sheet with that name. I was wondering how I could get this program to open an excel document with any sheet name. One that I may not know.
You can get all the sheets' names like so..
public string[] GetExcelSheetNames(string excelFileName)
{
OleDbConnection con = null;
DataTable dt = null;
String conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFileName + ";Extended Properties=Excel 8.0;";
con= new OleDbConnection(conStr);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheetNames;
}

Categories

Resources