I have an issue to retrieve the columns names in an Excel sheet.
I have an Excel sheet with only 3 cells in the first row with these 3 values:
in A1: A
in B1: B
in C1: A.B.C
When I try to execute my method the label shows:
A,B,A#B#C
And not:
A,B,A.B.C
My Code:
protected void btnExecute_Click(object sender, EventArgs e)
{
string fullFileName = #"C:\TEST.xls";
List<string> columns = new List<string>();
string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", fullFileName);
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
// Retrieves the first sheet
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string firstSheet = dt.Rows[0]["TABLE_NAME"].ToString();
// Retrieves the list column name
string query = string.Format("SELECT TOP 1 * FROM [{0}]", firstSheet);
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataReader reader = cmd.ExecuteReader();
for (int i = 0; i < reader.FieldCount; i++)
{
columns.Add(reader.GetName(i));
}
}
lblCols.Text = string.Join(",", columns.ToArray());
}
Do you have an idea to fix this issue??
Thanks in advance.
Daniel
Try this OleDBAdapter Excel QA I posted via stack overflow.
I just tested this and it picked up "A.B.C" from a sample .xls you described.
i.e. add the following to the bottom for a quick test:
Object o = ds.Tables["xlsImport"].Rows[0]["LocationID"];
Object oa = ds.Tables["xlsImport"].Rows[0]["PartID"];
Object row0Col3 = ds.Tables["xlsImport"].Rows[0][2];
string valLocationID = o.ToString();
string valPartID = oa.ToString();
string rowZeroColumn3 = row0Col3.ToString();
Related
I am using the following code to open an excel file (XLS) and populate a DataTable with the first worksheet:
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", filename);
OleDbConnection connExcel = new OleDbConnection(connectionString);
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
var adapter = new OleDbDataAdapter("SELECT * FROM [" + SheetName + "]", connectionString);
var ds = new DataSet();
int count = 0;
adapter.Fill(ds, SheetName);
DataTable dt = ds.Tables[0];
It works only when the file is already open in Ms Excel. Why could that be?
If the file is not open, I get an error message (on line connExcel.Open): External table is not in the expected format.
I'm facing the same problem and accordingly to this site, many developers are struggling for the same:
-When I try read Excel with OLE DB all values are empty
-Can't connect to excel file unless file is already open
Actually I'm using the classic connection string (note that I'm trying to read a 97/2003 file):
Provider=Microsoft.Jet.OLEDB.4.0; Data Source = " + GetFilename(filename) + "; Extended Properties ='Excel 8.0;HDR=NO;IMEX=1'
but the file can be read properly only if:
Is open in Excel or even in Word! (the file of course appears corrupted and unreadable, but then the OleDb procedure can read every line of the file), I didn't try with other Office apps
The file is not in read-only mode
I also tried to lock the file manually or to open it with other non-office applications, but the result is not the same. If I follow the two previous rules (file opened in Word or Excel in not read-only mode) I can see all the cells, otherwise it seems the first column is ignored completely (so F2 became F1, F3 became F2,... and F6, the last one, should became F5 otherwise it throws and out-of-index error).
In order to keep compatibility with OleDb without using 3rd parties libraries I found a very stupid workaround using Microsoft.Office.Interop.Excel assembly.
Excel.Application _app = new Excel.Application();
var workbooks = _app.Workbooks;
workbooks.Open(_filename);
// OleDb Connection
using (OleDbConnection conn = new OleDbConnection(connectionOleDb))
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = String.Format("SELECT * FROM [{0}$]", tableName);
OleDbDataReader myReader = cmd.ExecuteReader();
int i = 0;
while (myReader.Read())
{
//Here I read through all Excel rows
}
}
catch (Exception E)
{
MessageBox.Show("Error!\n" + E.Message);
}
finally
{
conn.Close();
workbooks.Close();
if (workbooks != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
_app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(_app);
}
}
Essentially the first 3 lines run an Excel instance that lasts exactly the time needed to OleDb to perform its tasks.
The last 4 lines, inside the finally block, let the Excel instance to be closed correctly, immediately after the task and avoid ghost Excel processes.
I repeat it's a very stupid workaround that also requires a 1,5 MB dll (Microsoft.Office.Interop.Excel.dll) to be added to the project.
Anyway seems impossible that OleDb cannot manage by itself the missing data...
I had the same problem. If the file was open the read was ok but if the file was closed... some thing was strange... in my case I received strange data from columns and values.. Debugging I found the name of the first sheet and was strange ["xls _xlnm#_FilterDatabase"] looking on the internet I found that's a name of hidden sheet and a trick to avoid read this sheet (HERE) and so I've implemented a method:
private string getFirstVisibileSheet(DataTable dtSheet, int index = 0)
{
string sheetName = String.Empty;
if (dtSheet.Rows.Count >= (index + 1))
{
sheetName = dtSheet.Rows[index]["TABLE_NAME"].ToString();
if (sheetName.Contains("FilterDatabase"))
{
return getFirstVisibileSheet(dtSheet, ++index);
}
}
return sheetName;
}
To me worked very well.
My complete example code is:
string excelFilePath = String.Empty;
string stringConnection = String.Empty;
using (OpenFileDialog openExcelDialog = new OpenFileDialog())
{
openExcelDialog.Filter = "Excel 2007 (*.xlsx)|*.xlsx|Excel 2003 (*.xls)|*.xls";
openExcelDialog.FilterIndex = 1;
openExcelDialog.RestoreDirectory = true;
DialogResult windowsResult = openExcelDialog.ShowDialog();
if (windowsResult != System.Windows.Forms.DialogResult.OK)
{
return;
}
excelFilePath = openExcelDialog.FileName;
using (DataTable dt = new DataTable())
{
try
{
if (!excelFilePath.Equals(String.Empty))
{
stringConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + ";Extended Properties='Excel 8.0; HDR=YES;';";
using (OleDbConnection conn = new OleDbConnection(stringConnection))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = getFirstVisibileSheet(dtSheet);
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
dt.TableName = sheetName;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
cmd = null;
conn.Close();
}
}
//Read and Use my DT
foreach (DataRow row in dt.Rows)
{
//On my case I need data on first and second Columns
if ((row.ItemArray.Count() < 2) ||
(row[0] == null || String.IsNullOrWhiteSpace(row[0].ToString()))
||
(row[1] == null ||String.IsNullOrWhiteSpace(row[1].ToString())))
{
continue;
}
//Get the number from the first COL
int colOneNumber = 0;
Int32.TryParse(row[0].ToString(), out colOneNumber);
//Get the string from the second COL
string colTwoString = row[1].ToString();
//Get the string from third COL if is a file path valid
string colThree = (row.ItemArray.Count() >= 3
&& !row.IsNull(2)
&& !String.IsNullOrWhiteSpace(row[2].ToString())
&& File.Exists(row[2].ToString())
) ? row[2].ToString() : String.Empty;
}
}
catch (Exception ex)
{
MessageBox.Show("Import error.\n" + ex.Message, "::ERROR::", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private string getFirstVisibileSheet(DataTable dtSheet, int index = 0)
{
string sheetName = String.Empty;
if (dtSheet.Rows.Count >= (index + 1))
{
sheetName = dtSheet.Rows[index]["TABLE_NAME"].ToString();
if (sheetName.Contains("FilterDatabase"))
{
return getFirstVisibileSheet(dtSheet, ++index);
}
}
return sheetName;
}
Is it failing on ToString(), like here?
Error is "Object reference not set to an instance of an object"
Does Convert.ToString() fix anything?
I am facing very strange issue. I have written class to which reads dbf file through oledb connection. I have downloaded dbf file from internet and it is reading all data correctly.
DBF file location: E:\Projects\SLAVE.DBF
I am facing following 2 issues
1) When I try to read other dbf file then it is reading only its table fields. it is not reading table fields data.
E:\Projects\line75.dbf
2) The other issue I am facing I have DBF files when I put these files in location then i am getting exception that
microsoft jet database engine does not find required object. Are you
missing some directive or path. E:\Projects\SDW_plnParcel.dbf
I am totally confused why it is reading SLAVE.DBF downloaded from internet correct, why it is not reading TABLE FIELDS DATA of line75.dbf and why it is throwing exception on SDW_plnParcel.dbf.
My class and one function for this class is as follows:
public class dbfHandler
{
public dbfHandler()
{
this.dbfTable = new DataTable();
}
public void initconnection(String filepath) // initialise dbconnection
{
String[] splitString = filepath.Split('\\');
this.filename = splitString[splitString.Length - 1];
splitString = splitString.Where(w => w != splitString[splitString.Length - 1]).ToArray();
String folderPath = String.Join("\\", splitString);
this.dbConnection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + folderPath + ";Extended Properties=dBase III");
this.dbConnection.Open();
}
public List<String> getcolumnvalues(int fieldIndex, List<int> rowIndexes)
{
List<String> columnvalues = new List<string>();
try
{
if(this.dbConnection.State == ConnectionState.Open)
{
string mySQL = "select * from " + this.filename; // dbf table name
OleDbCommand MyQuery = new OleDbCommand(mySQL, this.dbConnection);
OleDbDataReader reader = MyQuery.ExecuteReader();
int rowCount = 0;
while(reader.Read())
{
bool match = rowIndexes.Any(item => item == rowCount);
if(match == true)
{
String value = reader.GetValue(fieldIndex).ToString();
columnvalues.Add(value);
}
rowCount++;
}
reader.Close();
}
}
catch(Exception e)
{
throw e;
}
return columnvalues;
}
private String filename;
private DataTable dbfTable;
private OleDbConnection dbConnection;
}
When dealing with .DBF files, I have always had better results working with Microsoft's Visual Foxpro OleDb Provider
The connection string in simplified format
var connString = #"Provider=VFPOLEDB.1;Data Source=C:\SomePathToData;";
Now, instead of doing the data reader -- just to make sure you can get / see what you are expecting, try using a DataAdapter...
var da = new OleDataAdapter( yourSqlCmdObject, yourConnection)
var dt = new DataTable();
da.Fill(dt);
It should pull all columns from your query and all rows into proper data column types... Then you could cycle through all the column names, rows, etc..
foreach( DataColumn dc in dt.Columns )
var tmp = dc.ColumnName;
foreach( DataRow dr in dt.Rows )
{
object x = dr[0]; // get VALUE from column 0
x = dr["SpecificColumn"]; // if you KNOW the column name
}
Of which, you could tweak as needed. But if you only need a SPECIFIC column (or limited columns), change your query to quantify that.
Select OneField from YourTable...
I want to get excel sheet used data range by using oledb.
Code is below,
String strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=E:\\DOTNET\\CrsMicro\\CA.xls;"
+ "Extended Properties='Excel 8.0;HDR=Yes'";
using (OleDbConnection connExcel = new OleDbConnection(strExcelConn))
{
string selectString = "SELECT * FROM [CA$A1:D500]";
using (OleDbCommand cmdExcel = new OleDbCommand(selectString,connExcel))
{
cmdExcel.Connection = connExcel;
connExcel.Open();
DataTable dt=new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter();
adp.SelectCommand = cmdExcel;
adp.FillSchema(dt, SchemaType.Source);
adp.Fill(dt);
int range=dt.Columns.Count;
int row = dt.Rows.Count;
//var result = cmdExcel.ExecuteReader();
//DataTable dtExcelSchema;
//dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// string excelsheetname = dtExcelSchema.Rows[0].ItemArray[2].ToString();
connExcel.Close();
//string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
}
}
my sheet range is not always A1:D500, it may vary frequently. So i need to get the sheet range dynamically. I know this can be achieved by interop, but i need to do it in oledb. Any suggestion?
create a named range:
https://msdn.microsoft.com/EN-US/library/office/ff196817.aspx
and replace selectString to
"SELECT * FROM [CA$MyNamedRange]"
Hi I'm also working on same kind of problem in OLEDB C# excel, I found below solution. It works for me. But I'm new to C#, I'm not sure how efficient it is.
But it is satisfying my requirements so far. This may be helpful for others.
I was able to get dynamic range in an excel sheet from a browsed input excel file (make sure excel file doesn't contain hidden sheets). This works perfectly for excel workbook containing single sheet. I haven't tested with multiple sheets.
Range: A [stat value]: Column Name[0] // Returns all rows from start value till the column name.
Example: A1:M0 // It will return all rows from A1 till column M. So here no need to worry how many rows you have in your excel.
Just by giving Column Name[0] takes all rows from the starting till the column M.
So '0' will be our outer range.
//Code under actual c# clas file where we are uploading excel.
Excel_Common excelComm = new Excel_Common(); // object to Excel_Common class file
string rangeStringwithSHeet =excelComm.GetSheetName(filepath).ToString().Trim('\'') + GetRange(excelComm.GetSheetName(filepath), excelComm.ExcelConn(filepath));
queryForExcelInput = string.Format("SELECT * FROM [{0}]", rangeStringwithSHeet);
Econ1 = new OleDbConnection(excelComm.ExcelConn(filepath));
Econ1.Open();
dataExcelInputTable = new DataTable();
OleDbCommand oleDbCommand1 = new OleDbCommand(queryForExcelInput, Econ1);
OleDbDataAdapter oleDbDaAdapter1 = new OleDbDataAdapter(oleDbCommand1);
oleDbDaAdapter1.Fill(dataExcelInputTable);
Excel_Common class file has below methods:
//Get Range like A4:M30
public string GetRange(string SheetName, string excelConnectionString)
{
string rangeInput = "",rangeColName="";
int columnsCount = 0;
int rowStartRange = 0;
columnsCount = GetNumberOfColumnsInSheet(SheetName, excelConnectionString);
rowStartRange = GetStartRowRange(SheetName, excelConnectionString); // This is optional if you want always A1. just assign 1 here
while (columnsCount > 0)
{
columnsCount--;
rangeColName = (char)('A' + columnsCount % 26) + rangeColName;
columnsCount /= 26;
}
rangeInput = "A" + rowStartRange + ":" + rangeColName + "0";
return rangeInput;
}
// Get Sheet Name assuming only one sheet for workbook and no hidden sheets
public string GetSheetName(string filepath)
{
string sheetname = "";
String connect = ExcelConn(filepath);
OleDbConnection con = new OleDbConnection(connect);
con.Open();
DataTable tables = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow row in tables.Rows)
{
sheetname = row[2].ToString();
if (!sheetname.EndsWith("$"))
continue;
}
con.Close();
return sheetname;
}
// Get number of columns in a given sheet
public int GetNumberOfColumnsInSheet(string SheetName, string excelConnectionString)
{
int columnsCount = 0;
//If a valid excel file
if (!string.IsNullOrEmpty(excelConnectionString))
{
using (OleDbConnection conn = new OleDbConnection(excelConnectionString))
{
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, null);
if (dt.Rows.Count > 0)
columnsCount = dt.AsEnumerable().Where(a => a["TABLE_NAME"].ToString() == SheetName).Count();
conn.Close();
}
}
return columnsCount;
}
// Get the first row count in sheet contains some keyword . This method call is optional if you always want A1. Here I need to check some keyword exist and from there only I have to start something like A4
public int GetStartRowRange(string SheetName, string excelConnectionString)
{
int rowStartRange = 1;
//If a valid excel file
if (!string.IsNullOrEmpty(excelConnectionString))
{
using (OleDbConnection conn = new OleDbConnection(excelConnectionString))
{
string colValue;
conn.Open();
string cmdstr = "select * from [" + SheetName + "]";
OleDbCommand com = new OleDbCommand(cmdstr, conn);
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(com);
da.Fill(dt);
// get first row data where it started
foreach (DataRow dataRow in dt.Rows)
{
colValue = dataRow[0].ToString();
if ((colValue.Contains("Value1") || colValue.Contains("Value2") || colValue.Contains("Value3")) && (string.IsNullOrEmpty(dataRow[1].ToString()) == false))
{
rowStartRange = rowStartRange + 1;
break;
}
else
{
rowStartRange = rowStartRange + 1;
}
}
conn.Close();
}
}
return rowStartRange;
}
// Connection to excel document
public string ExcelConn(string FilePath)
{
string constr = "";
string extension = Path.GetExtension(FilePath);
//Checking for the extentions, if XLS connect using Jet OleDB
if (extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
{
constr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=\"Excel 12.0;IMEX=1;HDR=YES\"", FilePath);
}
//Use ACE OleDb if xlsx extention
else if (extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
{
constr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=YES\"", FilePath);
}
return constr;
} // end of ExcelConn method
I am using following code to update an Excel file into SQL Server. Code is working but it is not able to insert first row into table.
OleDbConnection OleDb = new OleDbConnection(ConnectionString);
OleDbCommand OleDbCmm = new OleDbCommand(Query,OleDb);
OleDbDataReader OleDbdr;
OleDb.Open();
if (OleDb.State == ConnectionState.Open)
{
OleDbdr = OleDbCmm.ExecuteReader();
SqlBulkCopy BulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["connstring"].ToString());
BulkCopy.DestinationTableName = "TempTable";
if (OleDbdr.Read())
{
BulkCopy.WriteToServer(OleDbdr);
}
}
OleDb.Close();
Even I was facing same problem, this is because I was using Read() Method like below.
while (dr.Read()) {
bulkcopy.WriteToServer(dr);
}
Solution to above problem is remove dr.Read() method and while loop
use
bulkcopy.WriteToServer(dr)
without any condition and Read() Method.
One possible reason for this may be that you've indicated in your connection string that first row contains column names (HDR=YES) thus that row is not treated as containing data.
EDIT
Another possible reason for this would be the call to OleDbDataReader.Read() method before passing the reader to SqlBulkCopy object. MSDN states:
The copy operation starts at the next available row in the reader. Most of the time, the reader was just returned by ExecuteReader or a similar call, so the next available row is the first row.
Thus, in your case you should not call OleDbdr.Read() because this advances the reader to the first row; you should let BulkCopy call Read() and it will start reading from the first row.
Your code should be:
OleDbdr = OleDbCmm.ExecuteReader();
SqlBulkCopy BulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["connstring"].ToString());
BulkCopy.DestinationTableName = "TempTable";
BulkCopy.WriteToServer(OleDbdr);
You need to set header for the Excel to sql as I have done in my
string conn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Your D S+ ";" +
"Extended Properties=Excel 8.0;";
OleDbConnection sSourceConnection = new OleDbConnection(conn);
using (sSourceConnection)
{
DataTable dtExcelData = new DataTable();
string[] SheetNames = GetExcelSheetNames(strFileName);
string[] preColumnHeader = new string[]{ "CarrierId", "StateId", "TerrCd", "ProgramId", "ClassId",
"PremTypeID","Limit50_100", "Limit100_100", "Limit100_200", "Limit300_300", "Limit300_600",
"Limit500_500","Limit500_1mil", "Limit1mil_1mil", "Limit1mil_2mil", "OtherParameter" };
sSourceConnection.Open();
string strQuery = string.Empty;
strQuery = "SELECT * FROM [" + SheetNames[0] + "]";
OleDbDataAdapter oleDA = new OleDbDataAdapter(strQuery, sSourceConnection);
oleDA.Fill(dtExcelData);
sSourceConnection.Close();
string[] colName = new string[dtExcelData.Columns.Count];
int i = 0;
foreach (DataColumn dc in dtExcelData.Columns)
{
colName[i] = dc.ColumnName;
i++;
}
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connStr))
{
bulkCopy.DestinationTableName = "tbl_test";
bulkCopy.WriteToServer(dtExcelData);
}
}
i needed to create a form in which i hav to browse and open mdb files ---> i did this part usin oprnfile dialogue!
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog oDlg = new OpenFileDialog();
oDlg.Title = "Select MDB";
oDlg.Filter = "MDB (*.Mdb)|*.mdb";
oDlg.RestoreDirectory = true;
string dir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
oDlg.InitialDirectory = dir;
DialogResult result = oDlg.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = oDlg.FileName.ToString();
}
}
**this is my code so far!!!
now i need to make 3 list boxes!!
1st one to display the table names of the db!
2nd to to display field names when clicked on table name!!!
3rd to display attributes on fiels on clickin on it!
v can edit the attribute values and on clickin of save button it should update the database!!!
This class should get you the information you need.
public static class DatabaseInfoCollector
{
public static System.Collections.Generic.List<string> GetTables(string file)
{
System.Data.DataTable tables;
using(System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file))
{
connection.Open();
tables = connection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,new object[]{null,null,null,"TABLE"});
}
System.Collections.Generic.List<string> Tables = new System.Collections.Generic.List<string>();
for (int i = 0; i < tables.Rows.Count; i++)
{
Tables.Add(tables.Rows[i][2].ToString());
}
return Tables;
}
public static System.Collections.Generic.List<string> GetColumnNames(string file, string table)
{
System.Data.DataTable dataSet = new System.Data.DataTable();
using(System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file))
{
connection.Open();
System.Data.OleDb.OleDbCommand Command = new System.Data.OleDb.OleDbCommand("SELECT * FROM " + table,connection);
using(System.Data.OleDb.OleDbDataAdapter dataAdapter = new System.Data.OleDb.OleDbDataAdapter(Command))
{
dataAdapter.Fill(dataSet);
}
}
System.Collections.Generic.List<string> columns = new System.Collections.Generic.List<string>();
for(int i = 0; i < dataSet.Columns.Count; i ++)
{
columns.Add(dataSet.Columns[i].ColumnName);
}
return columns;
}
}
Fill the tables list like this.
System.Collections.Generic.List<string> Tables = DatabaseInfoCollector.GetTables(textBox1.Text);
foreach(string table in Tables)
{
cboTable.Items.Add(table);
}
Fill the columns like this.
System.Collections.Generic.List<string> Columns = DatabaseInfoCollector.GetColumnNames(textBox1.Text,cboTable.SelectedItem.ToString());
foreach(string column in Columns)
{
cboColumns.Items.Add(column);
}
You can also use this method to return a DataTable containing all kinds of information about each column.
public static System.Data.DataTable GetSchemaData(string file)
{
System.Data.DataTable columns;
using(System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file))
{
connection.Open();
columns = connection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Columns,new object[]{null,null,null,null});
}
return columns;
}
Use the System.Data.OleDb.* classes to get the data from the access file.
Example:
//Create the OleDbConnection object
//and associate it with our database
using(OleDbConnection conn = new OleDbConnection(
"PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source="+textBox1.Text)){
//Open the database connection
conn.Open();
//Create an OleDbCommand object and
//pass it the SQL read query and the connection to use
OleDbCommand cmd = new OleDbCommand(sqlstr,conn);
//Procure the OleDbDataReader object to browse the recordset
OleDbDataReader rdr = cmd.ExecuteReader();
//Keep reading records in the forward direction
while (rdr.Read())
{
//Use one of the various methods available to read the data
//Eg:- GetValue, GetValues, Item etc.
. . .
. . .
}
}
Use System.Data.OleDb to open a connection with new OleDbConnection(connectionString).
The connection string should be "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=[PathToMDBFile]"
var conn = new OleDbConnection(connectionString);
var ds = new DataSet();
var adapter = new OleDbDataAdapter("SELECT Column1 FROM Table1", conn);
conn.Open();
adapter.Fill(ds);
conn.Close();
var value = ds.Tables[0].Rows[0]["Column1"].ToString();
That will get you the first value in the column named Column1