Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. c# error

c# error

Scheduled Pinned Locked Moved C#
databasecsharphelp
21 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • U User3490

    i have the following code that appears an error

    string query_BranchExposureFactor = "SELECT BranchExposureFactor FROM Questionnaires_Table where Branch_ID = (SELECT Branch_ID FROM [MS Access;DATABASE=" + dialog.FileName + "].Questionnaires_Table1 Where ReferenceYear = '" + txtdateref.Text + "');";
    OleDbCommand cmd_BranchExposureFactor = new OleDbCommand(query_BranchExposureFactor, dbConnDest);

                        double branchExposureFactor = ((double)cmd\_BranchExposureFactor.ExecuteScalar());
    

    the error is : ---------------- Object reference not set to an instance of an object.

    L Offline
    L Offline
    Lost User
    wrote on last edited by
    #7

    If the rest of your application is written in a similar manner you are heading for serious trouble. Your SQL is wide open to injection attacks, you are not checking the user's input values and you are ignoring the possibility that any command could fail. You should rewrite the above to do the following:

    1. Check the content of the textboxes to see that they contain valid data.
    2. Use proper parameterised SQL queries.
    3. Split your SQL query into two parts so you first find whether the BranchID query returns a good result.
    4. Using the value returned from the BranchID query, check the return value of the second query for the BranchExposureFactor.
    5. Use the double.TryParse() method to check that you have a valid floating point value.

    Use the best guess

    U 1 Reply Last reply
    0
    • E Emmanuel Medina

      Have you verified that your query string returns the appropiate data? Does

      zebra88 wrote:

      dialog.FileName

      and

      zebra88 wrote:

      txtdateref.Text

      have appropiate values? Sounds to me that ExecuteScalar is returning null. According to the MSDN documentation[^] on the OleDbCommand: Return Value Type: System.Object The first column of the first row in the result set, or a null reference if the result set is empty. Check if it is indeed returning null, if it is, check your input.

      If you think you can do a thing or think you can't do a thing, you're right - Henry Ford Emmanuel Medina Lopez

      U Offline
      U Offline
      User3490
      wrote on last edited by
      #8

      string query_BranchExposureFactor = "SELECT BranchExposureFactor FROM Questionnaires_Table where Branch_ID = (SELECT Branch_ID FROM [MS Access;DATABASE=" + dialog.FileName + "].Questionnaires_Table1 Where ReferenceYear = '" + txtdateref.Text + "');";
      OleDbCommand cmd_BranchExposureFactor = new OleDbCommand(query_BranchExposureFactor, dbConnDest);

                          double branchExposureFactor = (double.TryParse()) (cmd\_BranchExposureFactor.ExecuteScalar().ToString());
      

      i have error to the following code

      double branchExposureFactor = (double.TryParse()) (cmd_BranchExposureFactor.ExecuteScalar().ToString());

      1 Reply Last reply
      0
      • L Lost User

        If the rest of your application is written in a similar manner you are heading for serious trouble. Your SQL is wide open to injection attacks, you are not checking the user's input values and you are ignoring the possibility that any command could fail. You should rewrite the above to do the following:

        1. Check the content of the textboxes to see that they contain valid data.
        2. Use proper parameterised SQL queries.
        3. Split your SQL query into two parts so you first find whether the BranchID query returns a good result.
        4. Using the value returned from the BranchID query, check the return value of the second query for the BranchExposureFactor.
        5. Use the double.TryParse() method to check that you have a valid floating point value.

        Use the best guess

        U Offline
        U Offline
        User3490
        wrote on last edited by
        #9

        OleDbConnection dbConnDest; dbConnDest = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= SystemA.accdb"); string query_select = "SELECT ReferenceYear FROM [MS Access;DATABASE=" + dialog.FileName + "].Questionnaires_Table1 Where ReferenceYear = '" + txtdateref.Text + "';"; OleDbCommand cmd_year = new OleDbCommand(query_select, dbConnDest); dbConnDest.Open(); string rfyear = cmd_year.ExecuteScalar().ToString(); if (rfyear == null) { MessageBox.Show(" file not found with this ref year ", "", MessageBoxButtons.OK); } dbConnDest.Close(); i have error in following row string rfyear = cmd_year.ExecuteScalar().ToString(); if the query is wrong appears the error: ------------------------------------------ Object reference not set to an instance of an object.

        L 3 Replies Last reply
        0
        • U User3490

          OleDbConnection dbConnDest; dbConnDest = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= SystemA.accdb"); string query_select = "SELECT ReferenceYear FROM [MS Access;DATABASE=" + dialog.FileName + "].Questionnaires_Table1 Where ReferenceYear = '" + txtdateref.Text + "';"; OleDbCommand cmd_year = new OleDbCommand(query_select, dbConnDest); dbConnDest.Open(); string rfyear = cmd_year.ExecuteScalar().ToString(); if (rfyear == null) { MessageBox.Show(" file not found with this ref year ", "", MessageBoxButtons.OK); } dbConnDest.Close(); i have error in following row string rfyear = cmd_year.ExecuteScalar().ToString(); if the query is wrong appears the error: ------------------------------------------ Object reference not set to an instance of an object.

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #10

          zebra88 wrote:

          Object reference not set to an instance of an object.

          And that is exactly the same cause/reason as your original problem.

          U 1 Reply Last reply
          0
          • L Lost User

            zebra88 wrote:

            Object reference not set to an instance of an object.

            And that is exactly the same cause/reason as your original problem.

            U Offline
            U Offline
            User3490
            wrote on last edited by
            #11

            ok

            1 Reply Last reply
            0
            • U User3490

              OleDbConnection dbConnDest; dbConnDest = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= SystemA.accdb"); string query_select = "SELECT ReferenceYear FROM [MS Access;DATABASE=" + dialog.FileName + "].Questionnaires_Table1 Where ReferenceYear = '" + txtdateref.Text + "';"; OleDbCommand cmd_year = new OleDbCommand(query_select, dbConnDest); dbConnDest.Open(); string rfyear = cmd_year.ExecuteScalar().ToString(); if (rfyear == null) { MessageBox.Show(" file not found with this ref year ", "", MessageBoxButtons.OK); } dbConnDest.Close(); i have error in following row string rfyear = cmd_year.ExecuteScalar().ToString(); if the query is wrong appears the error: ------------------------------------------ Object reference not set to an instance of an object.

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #12

              zebra88 wrote:

              string rfyear = cmd_year.ExecuteScalar().ToString();

              The line contains multiple statements.

              object result = cmd_year.ExecuteScalar();
              if (DBNull.Value == result || null == result)
              throw new ApplicationException("Panic Now!");
              string rf_year = Convert.ToString(result);

              Put a breakpoint on the first line (place the cursor there and press F9), step trough the code (Hit F5 to run, hit F11 to step once you hit the breakpoint). On the second line of this example, examine the value of the result-variable by hovering your mouse above it in the IDE.

              Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

              U 1 Reply Last reply
              0
              • L Lost User

                zebra88 wrote:

                string rfyear = cmd_year.ExecuteScalar().ToString();

                The line contains multiple statements.

                object result = cmd_year.ExecuteScalar();
                if (DBNull.Value == result || null == result)
                throw new ApplicationException("Panic Now!");
                string rf_year = Convert.ToString(result);

                Put a breakpoint on the first line (place the cursor there and press F9), step trough the code (Hit F5 to run, hit F11 to step once you hit the breakpoint). On the second line of this example, examine the value of the result-variable by hovering your mouse above it in the IDE.

                Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                U Offline
                U Offline
                User3490
                wrote on last edited by
                #13

                i have 2 connectionstring in c# and 2 connection with 2 different access database in this query i use only one access db and one connection string but when i run the program it appears an error that say that could not found file dbfile.accdb what is the problem ? public bool findrefyear( string refyear) { bool findyear = false; //create new new access connection to the database OleDbConnection connd = new OleDbConnection(connection2); //Set the access command string OleDbCommand Cmd = new OleDbCommand("SELECT ReferenceYear FROM Questionnaires_Table1 Where ReferenceYear = '" + refyear + "';", connd); try { connd.Open(); Cmd.ExecuteNonQuery(); connd.Close(); findyear = true; } catch (OleDbException e) { MessageBox.Show(e.Message.ToString()); } i call the above code with this code: ----------------------------------------- ...

                if (txtdateref.Text != "" )
                {

                                   bool find\_data = qhandler.findrefyear(txtdateref.Text);
                            if (find\_data == false)
                              {
                
                               MessageBox.Show(" the record is not here ", "", MessageBoxButtons.OK);
                              }
                
                             else{
                           MessageBox.Show(" the record is here ", "", MessageBoxButtons.OK);
                                 }
                

                }

                L 1 Reply Last reply
                0
                • U User3490

                  OleDbConnection dbConnDest; dbConnDest = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= SystemA.accdb"); string query_select = "SELECT ReferenceYear FROM [MS Access;DATABASE=" + dialog.FileName + "].Questionnaires_Table1 Where ReferenceYear = '" + txtdateref.Text + "';"; OleDbCommand cmd_year = new OleDbCommand(query_select, dbConnDest); dbConnDest.Open(); string rfyear = cmd_year.ExecuteScalar().ToString(); if (rfyear == null) { MessageBox.Show(" file not found with this ref year ", "", MessageBoxButtons.OK); } dbConnDest.Close(); i have error in following row string rfyear = cmd_year.ExecuteScalar().ToString(); if the query is wrong appears the error: ------------------------------------------ Object reference not set to an instance of an object.

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #14

                  string rfyear = cmd_year.ExecuteScalar().ToString();

                  You are calling ToString() on the result of the call to ExecuteScalar(), and if that has returned null you will get the error you see. I Would suggest you re-read my previous suggestions, and the documentation for these methods, and start reorganising your code to include more robust error checking. Also, please put <pre> tags around your code, as I have done here, to make it more readable.

                  Use the best guess

                  U 1 Reply Last reply
                  0
                  • L Lost User

                    string rfyear = cmd_year.ExecuteScalar().ToString();

                    You are calling ToString() on the result of the call to ExecuteScalar(), and if that has returned null you will get the error you see. I Would suggest you re-read my previous suggestions, and the documentation for these methods, and start reorganising your code to include more robust error checking. Also, please put <pre> tags around your code, as I have done here, to make it more readable.

                    Use the best guess

                    U Offline
                    U Offline
                    User3490
                    wrote on last edited by
                    #15

                    i change my code now and looks like the following: now i have 2 connectionstring in c# and 2 connection with 2 different access database in this query i use only one access db and one connection string but when i run the program it appears an error that say that No database specified in connection string or IN clause. what is the problem ? public bool findrefyear( string refyear) { bool findyear = false; //create new new access connection to the database OleDbConnection connd = new OleDbConnection(connection2); //Set the access command string OleDbCommand Cmd = new OleDbCommand("SELECT ReferenceYear FROM Questionnaires_Table1 Where ReferenceYear = '" + refyear + "';", connd); try { connd.Open(); Cmd.ExecuteNonQuery(); connd.Close(); findyear = true; } catch (OleDbException e) { MessageBox.Show(e.Message.ToString()); } i call the above code with this code: ----------------------------------------- ... if (txtdateref.Text != "" ) { bool find_data = qhandler.findrefyear(txtdateref.Text); if (find_data == false) { MessageBox.Show(" the record is not here ", "", MessageBoxButtons.OK); } else{ MessageBox.Show(" the record is here ", "", MessageBoxButtons.OK); } }

                    L 1 Reply Last reply
                    0
                    • U User3490

                      i change my code now and looks like the following: now i have 2 connectionstring in c# and 2 connection with 2 different access database in this query i use only one access db and one connection string but when i run the program it appears an error that say that No database specified in connection string or IN clause. what is the problem ? public bool findrefyear( string refyear) { bool findyear = false; //create new new access connection to the database OleDbConnection connd = new OleDbConnection(connection2); //Set the access command string OleDbCommand Cmd = new OleDbCommand("SELECT ReferenceYear FROM Questionnaires_Table1 Where ReferenceYear = '" + refyear + "';", connd); try { connd.Open(); Cmd.ExecuteNonQuery(); connd.Close(); findyear = true; } catch (OleDbException e) { MessageBox.Show(e.Message.ToString()); } i call the above code with this code: ----------------------------------------- ... if (txtdateref.Text != "" ) { bool find_data = qhandler.findrefyear(txtdateref.Text); if (find_data == false) { MessageBox.Show(" the record is not here ", "", MessageBoxButtons.OK); } else{ MessageBox.Show(" the record is here ", "", MessageBoxButtons.OK); } }

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #16

                      zebra88 wrote:

                      an error that say that No database specified in connection string or IN clause.

                      So what is the content of your connection string?

                      Use the best guess

                      U 1 Reply Last reply
                      0
                      • L Lost User

                        zebra88 wrote:

                        an error that say that No database specified in connection string or IN clause.

                        So what is the content of your connection string?

                        Use the best guess

                        U Offline
                        U Offline
                        User3490
                        wrote on last edited by
                        #17

                        the content of connection string is a access database file that i don't want to locally connect with my c# because it is updated every time and user can import to the program with reference year the records that associated with this year i try to make it locally connected in c# and i observe that the database does not updated when i make it import again from my desktop on my laptop so the database that it is locally connected to my c# program has old record in spite of the two file it is the same but on different locations (locally- desktop and the other can be import to c#) . i use the following query to get the records with the associated reference year but i have the problem that i said previous : public DataTable findref2(string refyear) { try { //create new new connection to the database OleDbConnection conn = new OleDbConnection(connectionstringA); //Set the command string string Cmd = ("SELECT ReferenceYear FROM Questionnaires_Table1 Where ReferenceYear = '" + refyear + "' "); //create new data adapter OleDbDataAdapter Adapter = new OleDbDataAdapter(Cmd, conn); //create new command builder OleDbCommandBuilder sqlCmdBuilder = new OleDbCommandBuilder(Adapter); dTable = new DataTable(); Adapter.Fill(dTable); conn.Close(); } catch (OleDbException e) { MessageBox.Show(e.ToString()); } //return the search results on a datatable return dTable; } how can i get data without make my database locally connected in my c# program and i have the possibility to get data when i import from anywhere on my laptop to c# program. i have already a form that i put the reference year and opened a window that i can choose the access db file and i can import to my c# program (because i move on my locally connected access database which is different from database i make import ) but only if the year i put previous is on access db file i choose. Now i try to make a select query to check if the reference year already exists on file but i have the error No database specified in connection string or IN clause maybe because i must make locally connection on c# but i don't want as i said previous. can you help me please?

                        L 1 Reply Last reply
                        0
                        • U User3490

                          the content of connection string is a access database file that i don't want to locally connect with my c# because it is updated every time and user can import to the program with reference year the records that associated with this year i try to make it locally connected in c# and i observe that the database does not updated when i make it import again from my desktop on my laptop so the database that it is locally connected to my c# program has old record in spite of the two file it is the same but on different locations (locally- desktop and the other can be import to c#) . i use the following query to get the records with the associated reference year but i have the problem that i said previous : public DataTable findref2(string refyear) { try { //create new new connection to the database OleDbConnection conn = new OleDbConnection(connectionstringA); //Set the command string string Cmd = ("SELECT ReferenceYear FROM Questionnaires_Table1 Where ReferenceYear = '" + refyear + "' "); //create new data adapter OleDbDataAdapter Adapter = new OleDbDataAdapter(Cmd, conn); //create new command builder OleDbCommandBuilder sqlCmdBuilder = new OleDbCommandBuilder(Adapter); dTable = new DataTable(); Adapter.Fill(dTable); conn.Close(); } catch (OleDbException e) { MessageBox.Show(e.ToString()); } //return the search results on a datatable return dTable; } how can i get data without make my database locally connected in my c# program and i have the possibility to get data when i import from anywhere on my laptop to c# program. i have already a form that i put the reference year and opened a window that i can choose the access db file and i can import to my c# program (because i move on my locally connected access database which is different from database i make import ) but only if the year i put previous is on access db file i choose. Now i try to make a select query to check if the reference year already exists on file but i have the error No database specified in connection string or IN clause maybe because i must make locally connection on c# but i don't want as i said previous. can you help me please?

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #18

                          I'm not sure that I understand completely but it sounds as if you are trying to access a database file by copying it from one location to another before extracting or updating its records. You would be better using a database system that you can access remotely, like SQL Server.

                          zebra88 wrote:

                          but i have the error No database specified in connection string or IN clause

                          And again I would ask, what is the actual content of your connection string? Using your debugger would help you diagnose this problem much faster than posting questions here.

                          Use the best guess

                          1 Reply Last reply
                          0
                          • U User3490

                            the user must input to the form a reference year and must choose an access file that the program have to take some record from this file with this reference year and add to another access file with insert query but sometimes maybe the user choose a year that does not be in access file. How can i verify that when the query has return null will must return a message to the user that the year that has enter does not exist in access file ?? yes dialog.FileName and txtdateref.Text has the appropriate values.

                            E Offline
                            E Offline
                            Emmanuel Medina
                            wrote on last edited by
                            #19

                            For starters, you should validate the values both in the FileDialog and the TextBox (check that the file exists and check the textbox's text is actually a number, at the very least) then after building your query and preparing your command, store the result from ExecuteScalar in an object variable, then check that for null, if it is null, present an error message, if its not, then cast it to whatever its type should be.

                            If you think you can do a thing or think you can't do a thing, you're right - Henry Ford Emmanuel Medina Lopez

                            U 1 Reply Last reply
                            0
                            • E Emmanuel Medina

                              For starters, you should validate the values both in the FileDialog and the TextBox (check that the file exists and check the textbox's text is actually a number, at the very least) then after building your query and preparing your command, store the result from ExecuteScalar in an object variable, then check that for null, if it is null, present an error message, if its not, then cast it to whatever its type should be.

                              If you think you can do a thing or think you can't do a thing, you're right - Henry Ford Emmanuel Medina Lopez

                              U Offline
                              U Offline
                              User3490
                              wrote on last edited by
                              #20

                              thanks i solve my c# problem :)

                              1 Reply Last reply
                              0
                              • U User3490

                                i have 2 connectionstring in c# and 2 connection with 2 different access database in this query i use only one access db and one connection string but when i run the program it appears an error that say that could not found file dbfile.accdb what is the problem ? public bool findrefyear( string refyear) { bool findyear = false; //create new new access connection to the database OleDbConnection connd = new OleDbConnection(connection2); //Set the access command string OleDbCommand Cmd = new OleDbCommand("SELECT ReferenceYear FROM Questionnaires_Table1 Where ReferenceYear = '" + refyear + "';", connd); try { connd.Open(); Cmd.ExecuteNonQuery(); connd.Close(); findyear = true; } catch (OleDbException e) { MessageBox.Show(e.Message.ToString()); } i call the above code with this code: ----------------------------------------- ...

                                if (txtdateref.Text != "" )
                                {

                                                   bool find\_data = qhandler.findrefyear(txtdateref.Text);
                                            if (find\_data == false)
                                              {
                                
                                               MessageBox.Show(" the record is not here ", "", MessageBoxButtons.OK);
                                              }
                                
                                             else{
                                           MessageBox.Show(" the record is here ", "", MessageBoxButtons.OK);
                                                 }
                                

                                }

                                L Offline
                                L Offline
                                Lost User
                                wrote on last edited by
                                #21

                                zebra88 wrote:

                                what is the problem ?

                                Dunno. Does "error" mean that it throws an exception that the access database cannot be found? If yes, then there's an error in your connectionstring. If no, does "error" mean that it displays the message "the record is not here"? Further, a "select" statement is a query. One would use the ExecuteReader method to read the dataset.

                                Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                                1 Reply Last reply
                                0
                                Reply
                                • Reply as topic
                                Log in to reply
                                • Oldest to Newest
                                • Newest to Oldest
                                • Most Votes


                                • Login

                                • Don't have an account? Register

                                • Login or register to search.
                                • First post
                                  Last post
                                0
                                • Categories
                                • Recent
                                • Tags
                                • Popular
                                • World
                                • Users
                                • Groups