Uploading excel in to SQL Server in ASP.NET - sql-server

When I try to upload an Excel sheet of data into SQL Server I get the following error first time it uploads well when I try to upload it shows the following error
Before uploading I am deleting files in the directory
string[] filePaths1 = Directory.GetFiles(Server.MapPath(#"Excel\"));
foreach (string filePath1 in filePaths)
File.Delete(filePath1);
The process cannot access the file
'C:\inetpub\vhosts\xyz.com\httpdocs\newofficework\Excel\super.xlsx'
because it is being used by another process.

You seem to be performing multiple actions here (1) Delete and then (2) Upload
How are you Uploading the files? If you are using the SaveAs method, then please ensure that you Dispose the same.
E.g. (fuExcel is my FileUpload control)
fuExcel.SaveAs(sUniqueFilePath); // string variable containing file path
fuExcel.Dispose();

The Page having a FileUpload control and the Upload button, on selecting the Excel file user needs to click on Upload button to store the data to Server. Here we are treating the uploaded file as database hence we need to create OLEDB connection to this file, from this connection will be created and the data is fetched to C# as DataTable. '[Sheet1$]' is the Name of the Worksheet where requires data is present.
string SourceConstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection con = new OleDbConnection(SourceConstr);
string query = "Select * from [Sheet1$]";
OleDbDataAdapter data = new OleDbDataAdapter(query, con);
data.Fill(dtExcel);
From this code connection will be created for the Excel file and the data in Sheet1 will be dumped to the dtExcel of type DataTable.
Note:'$' must be there after the worksheet name.
fileName = FileUpload1.ResolveClientUrl(FileUpload1.PostedFile.FileName);
int count = 0;
DataClassesDataContext conLinq = new DataClassesDataContext("Data Source=server name;Initial Catalog=Database Name;Integrated Security=true");
try
{
DataTable dtExcel = new DataTable();
string SourceConstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + fileName + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection con = new OleDbConnection(SourceConstr);
string query = "Select * from [Sheet1$]";
OleDbDataAdapter data = new OleDbDataAdapter(query, con);
data.Fill(dtExcel);
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
try
{
count += conLinq.ExecuteCommand("insert into table name values(" + dtExcel.Rows[i][0] + "," + dtExcel.Rows[i][1] + ",'" + dtExcel.Rows[i][2] + "',"+dtExcel.Rows[i][3]+")");
}
catch (Exception ex)
{
continue;
}
}
if (count == dtExcel.Rows.Count)
{
<--Success Message-->
}
else
{
<--Failure Message-->
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
conLinq.Dispose();
}

Add these two name space in your class file
using System.Data.OleDb;
using System.Data.SqlClient;
Use following code
public void importDataFromExcel(string excelFilePath)
{
//Declare Variables - Edit these based on your particular situation
string sSQLTable = "tDataMigrationTable";
// make sure your sheet name is correct, here sheet name is Sheet1, so you can change your sheet name if have different
string myExcelDataQuery = "Select StudentName,RollNo,Course from [Sheet1$]";
try
{
//Create our connection strings
string sExcelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFilePath + ";Extended Properties=" + "\"Excel 8.0;HDR=YES;\"";
string sSqlConnectionString = "SERVER=MyDatabaseServerName;USER ID=DBUserId;PASSWORD=DBUserPassword;DATABASE=DatabaseName;CONNECTION RESET=FALSE";
//Execute a query to erase any previous data from our destination table
string sClearSQL = "DELETE FROM " + sSQLTable;
SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);
SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);
SqlConn.Open();
SqlCmd.ExecuteNonQuery();
SqlConn.Close();
//Series of commands to bulk copy data from the excel file into our SQL table
OleDbConnection OleDbConn = new OleDbConnection(sExcelConnectionString);
OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);
OleDbConn.Open();
OleDbDataReader dr = OleDbCmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);
bulkCopy.DestinationTableName = sSQLTable;
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
OleDbConn.Close();
}
catch (Exception ex)
{
//handle exception
}
}

Related

Script task failed to generate dynamic Excel workbook

I want to load sql query(Number of column change every time)data in Excel workbook that create column header dynamically.
First i have create four variable
Table Customer_NA have some entries
And create Ado.net connection and configure server-name and database name
Drag Script task and and assign all 4 variable in ReadOnlyVariable.
Edit Script task and write code to generate excel sheet column dynamically
public void Main()
{
// TODO: Add your code here
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["User::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["User::FolderPath"].Value.ToString();
string TableName = Dts.Variables["User::TableName"].Value.ToString();
string SheetName = Dts.Variables["User::SheetName"].Value.ToString();
ExcelFileName = ExcelFileName + "_" + datetime;
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.16.0;" + "Data Source=" + FolderPath + ExcelFileName
+ ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//drop Excel file if exists
File.Delete(FolderPath + "\\" + ExcelFileName + ".xlsx");
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["Ado_Conn"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT * from " + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//MessageBox.Show(TableColumns);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["User::FolderPath"].Value.ToString() + "\\" +
Dts.Variables["User::ExcelFileName"].Value.ToString() + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
Same Ado_Conn connection name i have write in c# script still facing error
after successfully buid script and run package and got error
Please help me out
I hope i Explain the scnerio
The alert shows a generic error message, therefore it is not possible to pinpoint the cause of the error.
Consider to add this line into a CATCH block:
Dts.Events.FireError(0, "Script Task Example", exception.Message + "\r" + exception.StackTrace, String.Empty, 0);
Also, perhaps it makes sense, for now, temporarily disable writing logs into a custom log file since this operation by itself can cause errors and they will not be captured by try..catch...
So the edited version will look this way:
catch (Exception exception)
{
Dts.Events.FireError(0, "Script Task", exception.Message + "\r" + exception.StackTrace, String.Empty, 0);
// Create Log File for Errors
// using (StreamWriter sw = File.CreateText(Dts.Variables["User::FolderPath"].Value.ToString() + "\\" +
// Dts.Variables["User::ExcelFileName"].Value.ToString() + datetime + ".log"))
// {
// sw.WriteLine(exception.ToString());
// Dts.TaskResult = (int)ScriptResults.Failure;
// }
}
The real reason of the exception will be routed to SSIS logs and can be tracked via SSDT output window or native SSIS Catalog logging in case if the package is deployed to a server

How to import data from Excel sheet to database in c# with LINQ?

I have three columns in Excel sheet such as id, name, family.
I am using LINQ and i need to import data from Excel to database with coding instruction, i have 6500 records in Excel sheet
You can use below code to get all the data and then you can convert form DataTable to List. for below example to work you have Microsoft Access Database Engine 2010 Redistributable
should be installed
public static DataTable ReadExcelWithoutOffice(string filePath)
{
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=YES;TypeGuessRows=0;FirstRowHasNames=true;ImportMixedTypes=Text\""; ;
using (var conn = new OleDbConnection(connectionString))
{
conn.Open();
var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";
var adapter = new OleDbDataAdapter(cmd);
var ds = new DataSet();
adapter.Fill(ds);
return ds.Tables[0];
}
}
}
Thank you all for your answer.
I found my problem. Here is the code :
string pach = #"D:\C# Projects\ex.xlsx";
var excelData = new ExcelQueryFactory(pach);
var data = from x in excelData.Worksheet<xlsdata>("MySheet")
select x;
DataClassesDataContext db = new DataClassesDataContext();
foreach (var d in data)
{
db.tbl_infos.InsertOnSubmit(new tbl_info
{
id = d.id,
name = d.name,
family = d.family
});
}
db.SubmitChanges();
You will need to import and reference OpenXML, open the sheets, sheet, worksheet, IIRC - then parse through your columns into strings.
OpenXML
Then create a SQL Data Adapter and all of that, to use either a ConnectionString or SQLConnection, fire up a parameterized query, and it's in the database.
SQL Example

Stored Procedure returns a temporary table that I need to convert to a CSV file

I basically have a stored procedure that I call through a method:
Time_Tracker.BLL.ResultsManager.GetCSV(Convert.ToDateTime("2014-01-11"));
It returns 8 columns of data ranging from 25 to 150 records.
I need to be able to convert it to a CSV file to a path of the users choosing. I am able to get it into my code behind as an array ( Results[] TEST = new Results[25]; ) and have verified that the data is O.K. I see plenty of posts were they use a DataTable as a source to convert to CSV, but I am not sure how to load a DataTable from the method that calls the stored procedure. Same thing with DataGridView, not sure how to load the data into a DataGridView either.
I have also seen methods were they use SqlDataAdapter to populate a DataTable. Since I use methods to that work directly with stored procedures, I don't want to have to use SqlDataAdapter and provide the database configuration info each time.
IF someone could help me load it into a DataTable or DataGridView, I think I can figure it out from there.
Thank you in advance.
Eric
Just define a data table and use the load command to move the data from the reader to the data table.
http://msdn.microsoft.com/en-us/library/d7125bke.aspx
This is right from MSDN. I added two lines to load a data table.
-- Code from msdn
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
SqlDataReader reader = cmd.ExecuteReader();
-- This is my addition
DataTable dt = new DataTable();
dt.Load(reader);
sqlConnection1.Close();
I still do not understand what you are trying to do. You can create a data table, xml record set, via coding.
The code below can be used to translate an array to a DataTable. Some work is needed on your side to add your details.
http://msdn.microsoft.com/en-us/library/skef0k7a(v=vs.110).aspx
// Create sample Customers table.
DataTable table = new DataTable();
table.TableName = "Customers";
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { 0, "Mary" });
table.Rows.Add(new object[] { 1, "Andy" });
table.Rows.Add(new object[] { 2, "Peter" });
table.AcceptChanges();
return table;
I hope this helps. If not, I still do not get the business requirement.
I figured it out (See Below). I will mark this as solved and once again, Thank You for your help !
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
if (dr[i] is DateTime)
{
if (((DateTime)dr[i]).TimeOfDay.TotalSeconds == 0) // Time Since Midnight (in Seconds)
{
sw.Write(((DateTime)dr[i]).ToString("yyyy-MM-dd"));
}
}
else
{
sw.Write(dr[i].ToString());
}
}
if (i < iColCount - 1) sw.Write(",");
}
sw.Write(sw.NewLine);
}
Here is what I ended up doing for anyone else looking for help:
protected void btnCSV_Click(object sender, EventArgs e)
{
try
{
// HATE EXPOSING THE DATABASE CONNECTION THIS WAY !!!
SqlConnection sqlConnection1 = new SqlConnection(DAL.DBUtils.SqlConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "[dbo].[usp.CSV_OUT]";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DateBeg", Time_Tracker.Utilities.TimeCard_Start_Date());
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
sqlConnection1.Close();
ExportToCSV(dt, ConfigurationManager.AppSettings["CSVPath"].ToString(), "CSV_Hours_Data_" + Time_Tracker.Utilities.TimeCard_Start_Date().AddDays(+6).ToString("MM_dd_yyyy") + ".csv");
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}
public static void ExportToCSV(DataTable dt, string strFilePath, string fileName)
{
try
{
var sw = new StreamWriter(strFilePath + fileName, false);
// Write the headers.
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1) sw.Write(",");
}
sw.Write(sw.NewLine);
// Write rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string output = dr[i].ToString();
if (dr[i] is DateTime)
{
if (((DateTime)dr[i]).TimeOfDay.TotalSeconds == 0) // Time Since Midnight (in Seconds)
{
output = (((DateTime)dr[i]).ToString("yyyy-MM-dd"));
}
}
if (output.Contains(";") || output.Contains("\""))
output = '"' + output.Replace("\"", "\"\"") + '"';
if (Regex.IsMatch(output, #"(?:\r\n|\n|\r)"))
output = string.Join(" ", Regex.Split(output, #"(?:\r\n|\n|\r)"));
sw.Write(output);
}
if (i < iColCount - 1) sw.Write(",");
}
sw.Write(sw.NewLine);
}
sw.Close();
// Causes Save As Dialog box to appear for user.
String FileName = fileName;
String FilePath = strFilePath;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath + FileName);
response.Flush();
response.End();
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}

While Uploading the Excel sheet table to SQL server table $ is not uploading with numbers but upload with text only

i want to upload the excel sheets data to the sql sever 2008, all my data i.e numbers and Alphabets from my excel sheet table are going to upload in the Database table but $ sign is not going to upload there as i have to use a currency as a column, $sign going to upload with text data but not with numbers.....pls let me knw abt this problem
this is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Xml;
using System.Configuration;
using System.IO;
using log4net.Config;
using log4net;
namespace ExcelUpload
{
class Program
{
static ILog log = LogManager.GetLogger(typeof(Program));
//Variable declarations
public static string strSqlConnection, strExcelDataQry, strSqlTable, strExcelFilePath, sexcelconnectionstring;
public static int intRows;
static void Main(string[] args)
{
#region GET PARAMS FROM CONFIG FILE
strSqlConnection = ConfigurationManager.ConnectionStrings["SQLConnection"].ToString();
strExcelFilePath = ConfigurationManager.AppSettings["ExcelFileName"].ToString();
string[] sqlSheets = ConfigurationManager.AppSettings["Sheets"].Split(',');
#endregion
#region SET CONNECTIONS
sexcelconnectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelFilePath + ";Extended Properties='Excel 12.0 xml;HDR=YES;'";
SqlConnection Sqlconn = new SqlConnection(strSqlConnection);
SqlBulkCopy bulkcopy = new SqlBulkCopy(strSqlConnection);
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
#endregion
XmlConfigurator.Configure();
log4net.ThreadContext.Properties["Context"] = "ExcelUpload";
try
{
log.Info("Started Execution of ExcelUpload Process");
foreach (string sqlSheetName in sqlSheets)
{
#region GET PARAMS FROM CONFIG FILE BASED ON CURRENT SHEET
strExcelDataQry = "select " + ConfigurationManager.AppSettings[sqlSheetName + "ColumnNames"] + " from [" + sqlSheetName + "$]";
strSqlTable = ConfigurationManager.AppSettings[sqlSheetName + "Table"];
intRows = Convert.ToInt32(ConfigurationManager.AppSettings[sqlSheetName + "RowsToExclude"].ToString());
#endregion
#region TRUNCATE TABLE
SqlCommand SqlCommand = new SqlCommand("TRUNCATE TABLE " + strSqlTable, Sqlconn);
Sqlconn.Open();
SqlCommand.ExecuteNonQuery();
Sqlconn.Close();
log.Info("Table " + strSqlTable + " Truncated Successfully");
#endregion
#region BULK COPY DATA
log.Info("Started processing the sheet " + sqlSheetName);
OleDbCommand oledbcmd = new OleDbCommand(strExcelDataQry, oledbconn);
oledbconn.Open();
DataSet ds = new DataSet();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(oledbcmd))
{
adapter.Fill(ds);
}
for (int iRow = 0; iRow < intRows; iRow++)
{
ds.Tables[0].Rows[iRow].Delete();
}
ds.Tables[0].AcceptChanges();
foreach (DataRow dr in ds.Tables[0].Rows)
{
foreach (DataColumn col in ds.Tables[0].Columns)
{
if (col.DataType == typeof(System.String))
{
dr[col] = dr[col].ToString().Trim();
}
}
}
bulkcopy.DestinationTableName = strSqlTable;
bulkcopy.WriteToServer(ds.Tables[0]);
oledbconn.Close();
log.Info("Sheet " + sqlSheetName + " successfully loaded to the table " + strSqlTable);
#endregion
}
log.Info("ExcelUpload Process completed successfully");
}
catch (System.Exception ex)
{
log.Info("Error while processing :- " + ex.Message);
}
finally
{
Sqlconn.Close();
oledbconn.Close();
}
}
}
}
If you want the currency column as Int you cant insert the $ symbols and decimal in it because defaultly integer datatype won't allow it.
So, to solve your problem make the curreny as Varchar and insert the data as something like $100.00
and while displaying it just show it.
And while doing calculations in front end remove the $ symbol using Contains keyword
and convert it into Double and do your calculations.
Hope it helps
Ok try this link for storing the data from excel to gridview(just for an example), you just change your need.
I also tested with that code to store the data which contains $ symbol in the cells and store it in the database also displaying the same data from the database with $ symbols in the same cells.
Have a look at it, it may be useful.
Load Gridview from Excel
just change the code for your need.

Hitting "COM object that has been separated from its underlying RCW cannot be used" error

I am trying to write a Windows Form program on top of .NET 4.0 and accessing Microsoft Access Database. I can read and write with no problem but sometimes, I get this error:
COM object that has been separated from its underlying RCW cannot be used.
I tried to call this method (GetIDBasedonTeamName) with different inputs twice (on the same thread). The second time this is run, I got that error.
OleDbConnection conn = new OleDbConnection();
OleDbConnection mDB = new OleDbConnection();
OleDbCommand comm = new OleDbCommand();
OleDbCommand cmd;
OleDbDataReader dr;
public void OpenConnection(string name) // always call this method first in other methods to initialise connection
{
conn.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Application.StartupPath + "\\AppData\\" + name + ".mdb;";
conn.Open();
comm.Connection = conn;
comm.Parameters.Clear();
}
public string GetIDBasedonTeamName(string teamName)
{
string toReturn = "";
try
{
OpenConnection("form");
comm.CommandText = "Select ID from TeamDetails WHERE TeamName=#teamName";
comm.Parameters.AddWithValue("TeamName", teamName);
dr = comm.ExecuteReader();
while (dr.Read())
{
toReturn = dr[0].ToString();
}
}
catch (OleDbException e)
{
string err = e.Message.ToString();
return null;
}
finally
{
}
conn.Close();
dr.Close();
return toReturn;
}
Exception happened on dr = comm.ExecuteReader();.
The method that was calling this method have this 2 lines inside:
InfoConfig.team1id = Convert.ToInt32(dbm.GetIDBasedonTeamName(cbxTeam1.Text));
InfoConfig.team2id = Convert.ToInt32(dbm.GetIDBasedonTeamName(cbxTeam2.Text));
What could be the cause? I read around and they mentioned not to use different threads but it is the same thread here.
Thanks,
Guo Hong
Building on Martin Liversage's answer:
public string GetIDBasedonTeamName(string teamName) {
var connString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Application.StartupPath + "\\AppData\\" + name + ".mdb;";
using (var conn = new OleDbConnection(connString)) {
conn.Open();
using (var cmd = conn.CreateCommand()) {
cmd.CommandText="Select ID from TeamDetails WHERE TeamName = #teamName";
cmd.Parameters.AddWithValue("TeamName", teamName);
using (var rdr = cmd.ExecuteReader()) {
if (rdr.Read()) {
return (string)rdr["TeamName"];
}
//if no valid results will return null
}
}
}
}
Instead of creating the objects only once and storing them in fields in your class you should create, use and close the objects in your method. It is probably the Close you call in the end the method that releases the underlying COM objects giving you the exception on the second call.

Resources