Closing Excel file after reading - excel-2007

Here is my code for opening the Excel file and reading the data, everything is working fine but what I would like is to close once the Excel file is read, how would i do that? I try Dispose the object but did not help.
public static DataTable ExcelWorkbook(string workbookName)
{
string connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", FILENAME);
string query = String.Format("select * from [{0}$]", workbookName);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataAdapter.Dispose();
DataTable myTable = dataSet.Tables[0];
if (myTable != null)
return myTable;
return null;
}

Your code should look sth like that:
OleDbConnection connection;
OleDbDataAdapter clientsAdapter new OleDbDataAdapter();
DataSet myDataSet = new DataSet();
connectionString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES""",FILENAME);
connection = new OleDbConnection(connectionString);
connection.Open();
clientsAdapter.SelectCommand = new OleDbCommand("SELECT * FROM [{0}$]", connection);
DataTable data = new DataTable("MyTable");
clientsAdapter.Fill(data);
myDataSet.Tables.Add(data);
connection.Close();
After the connection is closed, the excel file will be unlocked.

You are disposing the data adapter that read the data, not the reference to the Excel file itself.
Somewhere in your code, you will have opened the workbook. You need to call
workbook.Close();
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.workbookclass.close(v=office.14).aspx

Related

Load Records using the ADODB Connection with Datagridview

So i have here my codes for fetching informations from the database using
the listview, and now i want to use the datagridview but i dont know how
to do it using the ADODB Connectionenter image description here.
If you are able to use an Odbc connection instead try this to retreive your data
Dim conn As New OleDb.OleDbConnection("path to your database")
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim sql as String
Sql = "your SQL Query"
conn.Open()
cmd.Connection = conn
cmd.CommandText = Sql
da.SelectCommand = cmd
You can try using Odbc Connection in VB.Net.
First add new Module named Connection.vb
Imports System.Data.Odbc
Module Connection
Public Con As New OdbcConnection
Public Adpt As New OdbcDataAdapter
Public Ds As New DataSet
Public Cmd As OdbcCommand
Public Read As OdbcDataReader
Public Sql As String
Public StrCon As String = "Dsn=Your DSN Name in Odbc Connector"
Public Sub Connect()
Con = New OdbcConnection(StrCon)
If Con.State <> ConnectionState.Closed Then Con.Close()
Con.Open()
End Sub
End Module
And next don't forget to add Imports System.Data.Odbc in every form you have to connect to your Odbc Connection.
Simple Code to add item on ComboBox from Database.
Call Connect()
Cmd = New OdbcCommand("SELECT * FROM `category` ", Con)
cmbKategori.Items.Clear()
cmbKategori.AutoCompleteCustomSource.Clear()
Read = Cmd.ExecuteReader()
If Read.HasRows = True Then
While Read.Read()
cmbKategori.AutoCompleteCustomSource.Add(Read("name_category"))
cmbKategori.Items.Add(Read("name_category"))
End While
End If

Is filling a DataTable necessary for just setting variables with 2 column values?

I am trying to improve performance of an application, I have a case where a common SPROC is being used but is it necessary to fill a DataTable just to set 2 variable values?
Is there anything more efficient?
Dim Conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DB").ConnectionString)
Dim CmdUsers As SqlCommand = New SqlCommand("uspGetUsers", Conn)
CmdUsers.CommandType = CommandType.StoredProcedure
CmdUsers.Parameters.Add(New SqlParameter("#UserName", Session("UserID")))
Dim da As SqlDataAdapter = New SqlDataAdapter
Dim dtUserInfo As DataTable = New DataTable
da = New SqlDataAdapter(CmdUsers)
da.Fill(dtUserInfo)
isParent = dtUserInfo.Rows(0)("IsAdmin")
UserVal = dtUserInfo.Rows(0)("UserVal")
A SqlDataReader is the fastest way to read data from a query. Try the following:
Using conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DB").ConnectionString)
conn.Open()
Using cmd As New SqlCommand("uspGetUsers", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#UserName", Session("UserID"))
Using reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
isParent = reader("IsAdmin")
UserVal = reader("UserVal")
End While
End Using
End Using
End Using
You may need to parse the data to the correct types.
Also, note the use of Using to automatically dispose of the connection, command and reader objects: http://msdn.microsoft.com/en-GB/library/htd05whh.aspx

Showing data in textbox

I am trying to get data from a database (which I have done and know that works)
However I want to push the data into a variable.
I can not see what is wrong, at the moment there is a mistake around "cmd.select" so if someone could point me in the right direction that would be great!
Dim cn As SqlConnection = New SqlConnection()
Dim cmd As SqlCommand = New SqlCommand()
Dim sqladp As New SqlDataAdapter()
Dim ds As New DataSet()
cmd.Parameters.Clear()
cn.ConnectionString = ConfigurationManager.ConnectionStrings("PemcoConnectionString").ConnectionString
cmd.Connection = cn
GridView2.Visible = True
cmd.Connection = cn
cmd.CommandText = "spUserResultsDetails"
cmd.CommandType = CommandType.StoredProcedure
Session.Item("ID") = (sender.SelectedValue.ToString)
cmd.Parameters.AddWithValue("#ID", Session.Item("ID"))
For Each datarow As Data.DataRowView In cmd.Select(DataSourceSelectArguments.Empty)
sEmailAddress = datarow("UserEmail")
Next
sqladp.SelectCommand = cmd
sqladp.Fill(ds)
There are many things that need improvement, this should work:
Using cn = New SqlConnection(ConfigurationManager.ConnectionStrings("PemcoConnectionString").ConnectionString))
Using da = New SqlDataAdapter("spUserResultsDetails", cn)
da.SelectCommand.CommandType=CommandType.StoredProcedure
da.SelectCommand.Parameters.AddWithValue("#ID", CInt(Session.Item("ID")))
Dim table = New Data.DataTable()
da.Fill(table)
GridView2.DataSource = table
GridView2.DataBind()
End Using
End Using
A summary:
use the using statement always to ensure that disposable objects are getting disposed (closed) even on error
use a SqldataAdapter if you want to fill a DataTable, you don't need to open/close it with fill, use it's SelectCommand property to get a reference to the SqlCommand
set the table as DataSource of your GridView and DataBind it
if you use AddWithValue you should cast the passed objects to the correct type, otherwise the correct type cannot be inferred

operator/operand type mismatch when update dbf file

i have a program needs to update data in dbf file. but it keeps appear error 'operator/operand type mismatch'. here is sample code :
Dim con As OleDbConnection = New OleDbConnection("Provider=vfpoledb;Data Source=C:\folder\paytran.dbf;Collating Sequence=machine;")
Try
Dim strSQL As String = "UPDATE paytran.dbf SET workhr = 20 WHERE empno = 102"
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
con.Open()
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
' Using DataAdapter object fill data from database into DataSet object
myDA.Fill(myDataSet, "MyTable")
' Binding DataSet to DataGridView
DGV.DataSource = myDataSet.Tables("MyTable").DefaultView
con.Close()
con = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message, "Error Select Data")
Finally
If con IsNot Nothing Then
con.Close()
End If
End Try
please help me..
Its your connection string. The connection string should only have to point to the PATH where the data files are located, then all the SQL based commands will by default be able to see any .DBF tables IN that path (or forward if subpaths exists).
Data Source=C:\folder
instead of
Data Source=C:\folder\paytran.dbf
So, now if you have 30 tables in the "C:\folder", you can now query from ALL of them as needed.
You need to explicitly open and close the DBF. Try:
Dim strSQL As String = "Use paytran in 0 shared;UPDATE paytran SET workhr = 20 WHERE empno = 102;use in select('paytran')"

Save RTF data in My Sql database

Please tell me how to save and show Richtextbox's data in database and retrive it in saved format and which datatype should be used to save that data. i am using vb.net and MY SQL
if your data contains image/icons or some special symbols then its better to go for BLOB otherwise you can go with varchar datatype.
You can use the BLOB datatype.
Your RTF Data feild should be "Memo".
private void InsertToMemo()
{
using (OleDbConnection oleDbConn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\AD.mdb"))
{
OleDbCommand oleDbCmd = new OleDbCommand("insert into Table2 values(1,'" + this.richTextBox1.Rtf + "')", oleDbConn);
oleDbCmd.Connection.Open();
oleDbCmd.ExecuteNonQuery();
}
}
private void ReadFormMemo()
{
using (OleDbConnection oleDbConn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\AD.mdb"))
{
OleDbCommand oleDbCmd = new OleDbCommand("select Field1 from Table2", oleDbConn);
oleDbCmd.Connection.Open();
OleDbDataReader oleDbDataReader = oleDbCmd.ExecuteReader();
oleDbDataReader.Read();
this.richTextBox2.Rtf = oleDbDataReader.GetString(0);
}
}