Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Iam using VS2015. WinForms. First time when I execute, Once I click() the Form opens and simply it's working good. When I re-click() the button OpenFileDialog appears and it's get disappear immediately and the form get closed. Since I assumed the OleDbConnection not clearing. Thanks

<pre lang="C#">OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.FileName = String.Empty;
    openFileDialog1.Filter = "All files (*.*)|*.*";
    openFileDialog1.Title = "Select Your - Excel File :- ";
    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
            String MyExcelFile = openFileDialog1.FileName;

            //Below For XLSX Format
        String StrConn2 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + MyExcelFile + "; Extended Properties=\"Excel 12.0; HDR=YES; \"";

            String MyExcelSheet = "[Sheet1$]";
            String MySQLSelect = "select * from " + MyExcelSheet;
            System.Data.OleDb.OleDbConnection Cn1 = new System.Data.OleDb.OleDbConnection(StrConn2);
            System.Data.OleDb.OleDbDataAdapter Da1 = new System.Data.OleDb.OleDbDataAdapter(MySQLSelect, Cn1);
            Cn1 = null;


What I have tried:

Need to Clear the OledbConnection
Updated 6-Oct-22 18:24pm
Richard MacCutchan 7-Oct-22 4:17am    
Change your filter to only allow .xls and .xlsx files. That way you will be protected from entering bad files.
Paramu1973 7-Oct-22 21:47pm    
Always Richard MacCutchan is one of my favorite Guru!. Richard is always important to my career!
Richard MacCutchan 8-Oct-22 3:29am    
Thank you, I hope you succeed in your career.

1 solution

It's probably unrelated to the OleDbConnection itself, but we can't tell - none of that code would cause your form to close.

And we can't test it, because we have no access to your sytem, data, or other code in your app.

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900