1

I want to get specific data from Excel Sheet into winforms TextBoxes using search query. something like this "Search * from [Sheet1] where Staff Number=1234"

i tried this block of code but it's not working. I got an exception every time that says, Connection is not initialized properly.

try{
OleDbConnection con = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source=Test.xls;Extended Properties=Excel 8.0;");
           con.Open();
           OleDbCommand oleDbCommand = new OleDbCommand("SELECT * FROM [Sheet1] where Staff Number=1234");

              OleDbDataReader oleDbDataReader = oleDbCommand.ExecuteReader();


                   TxtDateOfBirth.Text = oleDbDataReader.GetString(1);
                   TxtName.Text=oleDbDataReader.GetString(2);
.
.
.
.
      }
           catch(Exception ex)
           {
               MessageBox.Show(ex.ToString());
           }

It's a simple form where the user will input the staff number and get the details of the person in relevant text boxes. Most of My Search results get me the solution of showing data into a datagridview but my problem is a bit different, i know i have to use data reader and execute it, but don't know why getting this problem.

Any Guide would be very helpful.

  • You don't actually need a DataReader. You can fill a DataTable and use the Columns names or indexes to assign their values to the properties of your Controls. + Is that sheet without header? See the connections strings [here](https://stackoverflow.com/a/54352568/7444103) (the first that came up). Also, note that you can use `ACE.OLEDB.12.0` instead of `Jet.OLEDB.4.0` to open an old `.xls` file (if, by chance, you're also reading the newer `.xlsx` format). – Jimi Mar 31 '19 at 06:08
  • Also, don't use field names with spaces (e.g., `Staff Number => [Staff Number]`). – Jimi Mar 31 '19 at 06:15
  • I also used the string without where Clause and it was retuning empty result. – Farhan Basheer. Mar 31 '19 at 06:24
  • Did you read what's inside the link I posted? Your connection string is not correct. Also, you haven't published the structure of the Excel data sheet. As already asked: does it have a header or not? Also, which is the data cells range? – Jimi Mar 31 '19 at 06:26
  • I am sorry but i don't understand what do you meant by headers? I have two rows i am using A1 To E1 as column names and A2 to E2 as their values. Should I adjust Column nae rows as headers? – Farhan Basheer. Mar 31 '19 at 06:27
  • `[B2:E2]`? what happened to `A2`? `[A1:E1]` is then the Header. Thus, your connection string also need `HDR=Yes`. Read that post. – Jimi Mar 31 '19 at 06:29
  • Yes i read, so i have to give complete path. – Farhan Basheer. Mar 31 '19 at 06:30
  • Edited my comment, typo mistake. I am using A2 to E2 as values. – Farhan Basheer. Mar 31 '19 at 06:31
  • It's obviously better to provide the full path. You always provide a full path to a file, since the current directory may change, but it's not really the point, here. If you have that file in your app's path, it'ld get it anyway. Read the post I linked in the first comment, about the connection strings. That's what your really need to fix. – Jimi Mar 31 '19 at 06:31

2 Answers2

0

It seems to me there are a few problems in your code:

1- You should place the full address of Excel file in your connection, instead of "test.xls".

2- There is a space between "Staff" and "Number" in your command. if the column name is "StaffNumber" there should not be any space. I recommend you to test the command without where clause first.

Navid Rsh
  • 308
  • 1
  • 6
  • 14
0

Tweaked your code a bit..

Improvements

Changed your connection string, added HDR=Yes; which indicates that the first row contains columnnames and also IMEX=1; which tells the driver to always read “intermixed” (numbers, dates, strings etc) data columns as text. These are generally helpful when working with staff dbs.

Problems

Added variables to make it cleaner and full path to your xls db file.

Added a $ after Sheet1 and also wrap [Staff Number] with [] as suggested in the comments by other helping users above.

Added oleDbDataReader.Read() to read through the result(s), as this was also missing in your code above.

Example code below works for me.

try 
{           
    var xlsDbPath= "C:\\Temp\\Test.xls"; //<-- Full name of path
    var connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsDbPath+ ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
    var query = "SELECT * FROM [Sheet1$] WHERE [Staff Number] = 1234";  //<-- Add $ after Sheet1 and fix 'Staff Number'?

    using (var con = new OleDbConnection(connStr))
    {
        con.Open();
        using (var oleDbCommand = new OleDbCommand(query, con))
        {
            using (var oleDbDataReader = oleDbCommand.ExecuteReader())
            {
                while (oleDbDataReader.Read())  //Read through results
                {
                     TxtDateOfBirth.Text = oleDbDataReader.GetString(1);
                     TxtName.Text = oleDbDataReader.GetString(2);
                     //...  //Remember if value is not string you will get error
                     //...  //so if not string use .GetValue(1).ToString();
                } 
            }
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}
Magic Mick
  • 1,475
  • 1
  • 21
  • 32
  • Thank you for this great help. i will test this code and mark your answer. I am using the upgraded version of excel sheet(2007 and onward) that's why i think i should use `Microsoft.Jet.OLEDB.12.0` and change the extension to xlsx . Is there any other change require? – Farhan Basheer. Apr 01 '19 at 16:02
  • Tried this code and getting this error, `Data type missmatch in criteria expression` and the line it's refering to is this `using (var oleDbDataReader = oleDbCommand.ExecuteReader())` – Farhan Basheer. Apr 01 '19 at 18:29
  • With xlsx (2007+) id recommend `"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"` as `Microsoft.ACE.OLEDB.12.0` is a newer version driver. As for the error, Im not sure how your columns are formatted (text. Numbers etc), so check here https://stackoverflow.com/questions/45861436/excel-sql-data-type-mismatch – Magic Mick Apr 01 '19 at 20:24
  • Please post your query? – Magic Mick Apr 02 '19 at 00:41
  • Worked like a charm! Thank you. – Farhan Basheer. Apr 02 '19 at 19:59