How do i convert an int retrieved from a database to string












2















I have a login form that I wanna select the userID (which is in the form of an int) from the database, and store it as a string.



string insertQuery = 
"SELECT UserID FROM Customers WHERE Email = @Email AND Password = @Password";

SqlCommand com = new SqlCommand(insertQuery, conn);

com.Parameters.AddWithValue("@Email", tbEmail.Text);
com.Parameters.AddWithValue("@Password", tbPassword.Text);

string result = (string)com.ExecuteScalar();


But after I login, I get this error:




System.InvalidCastException: 'Unable to cast object of type
'System.Int32' to type 'System.String'.











share|improve this question

























  • Like this: string insertQuery = "SELECT CONVERT(NVARCHAR(20),UserID) FROM Customers WHERE Email = @Email AND Password = @Password";

    – Prashant Pimpale
    Dec 28 '18 at 12:48






  • 1





    Instead of (string) in front if it, add .ToString() behind it.

    – Nyerguds
    Dec 28 '18 at 12:52






  • 1





    Why do you want to do that? What's wrong with keeping it an int?

    – Klaus Gütter
    Dec 28 '18 at 12:52











  • If the value is an integer then use an int to read it. This seems like an X-Y Problem.

    – David
    Dec 28 '18 at 12:58
















2















I have a login form that I wanna select the userID (which is in the form of an int) from the database, and store it as a string.



string insertQuery = 
"SELECT UserID FROM Customers WHERE Email = @Email AND Password = @Password";

SqlCommand com = new SqlCommand(insertQuery, conn);

com.Parameters.AddWithValue("@Email", tbEmail.Text);
com.Parameters.AddWithValue("@Password", tbPassword.Text);

string result = (string)com.ExecuteScalar();


But after I login, I get this error:




System.InvalidCastException: 'Unable to cast object of type
'System.Int32' to type 'System.String'.











share|improve this question

























  • Like this: string insertQuery = "SELECT CONVERT(NVARCHAR(20),UserID) FROM Customers WHERE Email = @Email AND Password = @Password";

    – Prashant Pimpale
    Dec 28 '18 at 12:48






  • 1





    Instead of (string) in front if it, add .ToString() behind it.

    – Nyerguds
    Dec 28 '18 at 12:52






  • 1





    Why do you want to do that? What's wrong with keeping it an int?

    – Klaus Gütter
    Dec 28 '18 at 12:52











  • If the value is an integer then use an int to read it. This seems like an X-Y Problem.

    – David
    Dec 28 '18 at 12:58














2












2








2








I have a login form that I wanna select the userID (which is in the form of an int) from the database, and store it as a string.



string insertQuery = 
"SELECT UserID FROM Customers WHERE Email = @Email AND Password = @Password";

SqlCommand com = new SqlCommand(insertQuery, conn);

com.Parameters.AddWithValue("@Email", tbEmail.Text);
com.Parameters.AddWithValue("@Password", tbPassword.Text);

string result = (string)com.ExecuteScalar();


But after I login, I get this error:




System.InvalidCastException: 'Unable to cast object of type
'System.Int32' to type 'System.String'.











share|improve this question
















I have a login form that I wanna select the userID (which is in the form of an int) from the database, and store it as a string.



string insertQuery = 
"SELECT UserID FROM Customers WHERE Email = @Email AND Password = @Password";

SqlCommand com = new SqlCommand(insertQuery, conn);

com.Parameters.AddWithValue("@Email", tbEmail.Text);
com.Parameters.AddWithValue("@Password", tbPassword.Text);

string result = (string)com.ExecuteScalar();


But after I login, I get this error:




System.InvalidCastException: 'Unable to cast object of type
'System.Int32' to type 'System.String'.








c# sql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 28 '18 at 13:06









Dmitry Bychenko

106k992132




106k992132










asked Dec 28 '18 at 12:46









Hashim AlshareefHashim Alshareef

213




213













  • Like this: string insertQuery = "SELECT CONVERT(NVARCHAR(20),UserID) FROM Customers WHERE Email = @Email AND Password = @Password";

    – Prashant Pimpale
    Dec 28 '18 at 12:48






  • 1





    Instead of (string) in front if it, add .ToString() behind it.

    – Nyerguds
    Dec 28 '18 at 12:52






  • 1





    Why do you want to do that? What's wrong with keeping it an int?

    – Klaus Gütter
    Dec 28 '18 at 12:52











  • If the value is an integer then use an int to read it. This seems like an X-Y Problem.

    – David
    Dec 28 '18 at 12:58



















  • Like this: string insertQuery = "SELECT CONVERT(NVARCHAR(20),UserID) FROM Customers WHERE Email = @Email AND Password = @Password";

    – Prashant Pimpale
    Dec 28 '18 at 12:48






  • 1





    Instead of (string) in front if it, add .ToString() behind it.

    – Nyerguds
    Dec 28 '18 at 12:52






  • 1





    Why do you want to do that? What's wrong with keeping it an int?

    – Klaus Gütter
    Dec 28 '18 at 12:52











  • If the value is an integer then use an int to read it. This seems like an X-Y Problem.

    – David
    Dec 28 '18 at 12:58

















Like this: string insertQuery = "SELECT CONVERT(NVARCHAR(20),UserID) FROM Customers WHERE Email = @Email AND Password = @Password";

– Prashant Pimpale
Dec 28 '18 at 12:48





Like this: string insertQuery = "SELECT CONVERT(NVARCHAR(20),UserID) FROM Customers WHERE Email = @Email AND Password = @Password";

– Prashant Pimpale
Dec 28 '18 at 12:48




1




1





Instead of (string) in front if it, add .ToString() behind it.

– Nyerguds
Dec 28 '18 at 12:52





Instead of (string) in front if it, add .ToString() behind it.

– Nyerguds
Dec 28 '18 at 12:52




1




1





Why do you want to do that? What's wrong with keeping it an int?

– Klaus Gütter
Dec 28 '18 at 12:52





Why do you want to do that? What's wrong with keeping it an int?

– Klaus Gütter
Dec 28 '18 at 12:52













If the value is an integer then use an int to read it. This seems like an X-Y Problem.

– David
Dec 28 '18 at 12:58





If the value is an integer then use an int to read it. This seems like an X-Y Problem.

– David
Dec 28 '18 at 12:58












6 Answers
6






active

oldest

votes


















3














You can try using like below



string result = Convert.ToString(com.ExecuteScalar());





share|improve this answer































    8














    What if the record doesn't exist (i.e. the cursor is empty)? Let's read and check if we have at least one record:



    // Keep Sql being readable
    string insertQuery =
    @"SELECT UserID
    FROM Customers
    WHERE Email = @Email
    AND Password = @Password";

    // Do not forget to dispose IDisposable
    using (SqlCommand com = new SqlCommand(insertQuery, conn)) {
    com.Parameters.AddWithValue("@Email", tbEmail.Text);
    com.Parameters.AddWithValue("@Password", tbPassword.Text);

    using (var reader = com.ExecuteReader()) {
    string result = reader.Read()
    ? Convert.ToString(reader[0]) // record exists
    : null; // cursor is empty

    //TODO: put relevant code which works with result here
    }
    }





    share|improve this answer































      1














      ExecuteScalar returns Object type and you can convert it into which ever type you like



      public override object ExecuteScalar ();


      You can call it's ToString() method and it returns string form of it's value.






      share|improve this answer































        1














        Try this,



        string result = string.Empty;

        SqlCommand com = new SqlCommand(..);
        ..
        object executedResult = com.ExecuteScalar();

        if(executedResult != null) {
        result = executedResult.ToString();
        }


        Hope helps,






        share|improve this answer































          1














          Probably the simplest solution would be (assuming query always return result):



          string result = com.ExecuteScalar().ToString();


          You can cast as nvarchar in your query also:



          string insertQuery = "SELECT cast(UserID as nvarchar) FROM Customers WHERE Email = @Email AND Password = @Password";





          share|improve this answer

































            0














            Below are my findings



                string userID;

            using(SqlConnection conn = new SqlConnection(connectionString))
            {
            string insertQuery = "SELECT UserID FROM Customers WHERE Email = @Email AND
            Password = @Password";
            SqlCommand com = new SqlCommand(insertQuery, conn);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Email", tbEmail.Text.ToString().Trim());
            com.Parameters.AddWithValue("@Password", tbPassword.Text.ToString().Trim());
            SqlDataReader reader = com.ExecuteReader();
            while(reader.Read())
            {
            userID = reader["UserID"].ToString();
            }
            }





            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53958845%2fhow-do-i-convert-an-int-retrieved-from-a-database-to-string%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              6 Answers
              6






              active

              oldest

              votes








              6 Answers
              6






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              3














              You can try using like below



              string result = Convert.ToString(com.ExecuteScalar());





              share|improve this answer




























                3














                You can try using like below



                string result = Convert.ToString(com.ExecuteScalar());





                share|improve this answer


























                  3












                  3








                  3







                  You can try using like below



                  string result = Convert.ToString(com.ExecuteScalar());





                  share|improve this answer













                  You can try using like below



                  string result = Convert.ToString(com.ExecuteScalar());






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 28 '18 at 12:58









                  sri harshasri harsha

                  1706




                  1706

























                      8














                      What if the record doesn't exist (i.e. the cursor is empty)? Let's read and check if we have at least one record:



                      // Keep Sql being readable
                      string insertQuery =
                      @"SELECT UserID
                      FROM Customers
                      WHERE Email = @Email
                      AND Password = @Password";

                      // Do not forget to dispose IDisposable
                      using (SqlCommand com = new SqlCommand(insertQuery, conn)) {
                      com.Parameters.AddWithValue("@Email", tbEmail.Text);
                      com.Parameters.AddWithValue("@Password", tbPassword.Text);

                      using (var reader = com.ExecuteReader()) {
                      string result = reader.Read()
                      ? Convert.ToString(reader[0]) // record exists
                      : null; // cursor is empty

                      //TODO: put relevant code which works with result here
                      }
                      }





                      share|improve this answer




























                        8














                        What if the record doesn't exist (i.e. the cursor is empty)? Let's read and check if we have at least one record:



                        // Keep Sql being readable
                        string insertQuery =
                        @"SELECT UserID
                        FROM Customers
                        WHERE Email = @Email
                        AND Password = @Password";

                        // Do not forget to dispose IDisposable
                        using (SqlCommand com = new SqlCommand(insertQuery, conn)) {
                        com.Parameters.AddWithValue("@Email", tbEmail.Text);
                        com.Parameters.AddWithValue("@Password", tbPassword.Text);

                        using (var reader = com.ExecuteReader()) {
                        string result = reader.Read()
                        ? Convert.ToString(reader[0]) // record exists
                        : null; // cursor is empty

                        //TODO: put relevant code which works with result here
                        }
                        }





                        share|improve this answer


























                          8












                          8








                          8







                          What if the record doesn't exist (i.e. the cursor is empty)? Let's read and check if we have at least one record:



                          // Keep Sql being readable
                          string insertQuery =
                          @"SELECT UserID
                          FROM Customers
                          WHERE Email = @Email
                          AND Password = @Password";

                          // Do not forget to dispose IDisposable
                          using (SqlCommand com = new SqlCommand(insertQuery, conn)) {
                          com.Parameters.AddWithValue("@Email", tbEmail.Text);
                          com.Parameters.AddWithValue("@Password", tbPassword.Text);

                          using (var reader = com.ExecuteReader()) {
                          string result = reader.Read()
                          ? Convert.ToString(reader[0]) // record exists
                          : null; // cursor is empty

                          //TODO: put relevant code which works with result here
                          }
                          }





                          share|improve this answer













                          What if the record doesn't exist (i.e. the cursor is empty)? Let's read and check if we have at least one record:



                          // Keep Sql being readable
                          string insertQuery =
                          @"SELECT UserID
                          FROM Customers
                          WHERE Email = @Email
                          AND Password = @Password";

                          // Do not forget to dispose IDisposable
                          using (SqlCommand com = new SqlCommand(insertQuery, conn)) {
                          com.Parameters.AddWithValue("@Email", tbEmail.Text);
                          com.Parameters.AddWithValue("@Password", tbPassword.Text);

                          using (var reader = com.ExecuteReader()) {
                          string result = reader.Read()
                          ? Convert.ToString(reader[0]) // record exists
                          : null; // cursor is empty

                          //TODO: put relevant code which works with result here
                          }
                          }






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Dec 28 '18 at 13:04









                          Dmitry BychenkoDmitry Bychenko

                          106k992132




                          106k992132























                              1














                              ExecuteScalar returns Object type and you can convert it into which ever type you like



                              public override object ExecuteScalar ();


                              You can call it's ToString() method and it returns string form of it's value.






                              share|improve this answer




























                                1














                                ExecuteScalar returns Object type and you can convert it into which ever type you like



                                public override object ExecuteScalar ();


                                You can call it's ToString() method and it returns string form of it's value.






                                share|improve this answer


























                                  1












                                  1








                                  1







                                  ExecuteScalar returns Object type and you can convert it into which ever type you like



                                  public override object ExecuteScalar ();


                                  You can call it's ToString() method and it returns string form of it's value.






                                  share|improve this answer













                                  ExecuteScalar returns Object type and you can convert it into which ever type you like



                                  public override object ExecuteScalar ();


                                  You can call it's ToString() method and it returns string form of it's value.







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Dec 28 '18 at 12:59









                                  uzay95uzay95

                                  6,2162489153




                                  6,2162489153























                                      1














                                      Try this,



                                      string result = string.Empty;

                                      SqlCommand com = new SqlCommand(..);
                                      ..
                                      object executedResult = com.ExecuteScalar();

                                      if(executedResult != null) {
                                      result = executedResult.ToString();
                                      }


                                      Hope helps,






                                      share|improve this answer




























                                        1














                                        Try this,



                                        string result = string.Empty;

                                        SqlCommand com = new SqlCommand(..);
                                        ..
                                        object executedResult = com.ExecuteScalar();

                                        if(executedResult != null) {
                                        result = executedResult.ToString();
                                        }


                                        Hope helps,






                                        share|improve this answer


























                                          1












                                          1








                                          1







                                          Try this,



                                          string result = string.Empty;

                                          SqlCommand com = new SqlCommand(..);
                                          ..
                                          object executedResult = com.ExecuteScalar();

                                          if(executedResult != null) {
                                          result = executedResult.ToString();
                                          }


                                          Hope helps,






                                          share|improve this answer













                                          Try this,



                                          string result = string.Empty;

                                          SqlCommand com = new SqlCommand(..);
                                          ..
                                          object executedResult = com.ExecuteScalar();

                                          if(executedResult != null) {
                                          result = executedResult.ToString();
                                          }


                                          Hope helps,







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Dec 28 '18 at 13:03









                                          BerkayBerkay

                                          3,25121126




                                          3,25121126























                                              1














                                              Probably the simplest solution would be (assuming query always return result):



                                              string result = com.ExecuteScalar().ToString();


                                              You can cast as nvarchar in your query also:



                                              string insertQuery = "SELECT cast(UserID as nvarchar) FROM Customers WHERE Email = @Email AND Password = @Password";





                                              share|improve this answer






























                                                1














                                                Probably the simplest solution would be (assuming query always return result):



                                                string result = com.ExecuteScalar().ToString();


                                                You can cast as nvarchar in your query also:



                                                string insertQuery = "SELECT cast(UserID as nvarchar) FROM Customers WHERE Email = @Email AND Password = @Password";





                                                share|improve this answer




























                                                  1












                                                  1








                                                  1







                                                  Probably the simplest solution would be (assuming query always return result):



                                                  string result = com.ExecuteScalar().ToString();


                                                  You can cast as nvarchar in your query also:



                                                  string insertQuery = "SELECT cast(UserID as nvarchar) FROM Customers WHERE Email = @Email AND Password = @Password";





                                                  share|improve this answer















                                                  Probably the simplest solution would be (assuming query always return result):



                                                  string result = com.ExecuteScalar().ToString();


                                                  You can cast as nvarchar in your query also:



                                                  string insertQuery = "SELECT cast(UserID as nvarchar) FROM Customers WHERE Email = @Email AND Password = @Password";






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Dec 28 '18 at 13:06

























                                                  answered Dec 28 '18 at 12:57









                                                  Pawel CzapskiPawel Czapski

                                                  1,2141917




                                                  1,2141917























                                                      0














                                                      Below are my findings



                                                          string userID;

                                                      using(SqlConnection conn = new SqlConnection(connectionString))
                                                      {
                                                      string insertQuery = "SELECT UserID FROM Customers WHERE Email = @Email AND
                                                      Password = @Password";
                                                      SqlCommand com = new SqlCommand(insertQuery, conn);
                                                      com.CommandType = CommandType.StoredProcedure;
                                                      com.Parameters.AddWithValue("@Email", tbEmail.Text.ToString().Trim());
                                                      com.Parameters.AddWithValue("@Password", tbPassword.Text.ToString().Trim());
                                                      SqlDataReader reader = com.ExecuteReader();
                                                      while(reader.Read())
                                                      {
                                                      userID = reader["UserID"].ToString();
                                                      }
                                                      }





                                                      share|improve this answer




























                                                        0














                                                        Below are my findings



                                                            string userID;

                                                        using(SqlConnection conn = new SqlConnection(connectionString))
                                                        {
                                                        string insertQuery = "SELECT UserID FROM Customers WHERE Email = @Email AND
                                                        Password = @Password";
                                                        SqlCommand com = new SqlCommand(insertQuery, conn);
                                                        com.CommandType = CommandType.StoredProcedure;
                                                        com.Parameters.AddWithValue("@Email", tbEmail.Text.ToString().Trim());
                                                        com.Parameters.AddWithValue("@Password", tbPassword.Text.ToString().Trim());
                                                        SqlDataReader reader = com.ExecuteReader();
                                                        while(reader.Read())
                                                        {
                                                        userID = reader["UserID"].ToString();
                                                        }
                                                        }





                                                        share|improve this answer


























                                                          0












                                                          0








                                                          0







                                                          Below are my findings



                                                              string userID;

                                                          using(SqlConnection conn = new SqlConnection(connectionString))
                                                          {
                                                          string insertQuery = "SELECT UserID FROM Customers WHERE Email = @Email AND
                                                          Password = @Password";
                                                          SqlCommand com = new SqlCommand(insertQuery, conn);
                                                          com.CommandType = CommandType.StoredProcedure;
                                                          com.Parameters.AddWithValue("@Email", tbEmail.Text.ToString().Trim());
                                                          com.Parameters.AddWithValue("@Password", tbPassword.Text.ToString().Trim());
                                                          SqlDataReader reader = com.ExecuteReader();
                                                          while(reader.Read())
                                                          {
                                                          userID = reader["UserID"].ToString();
                                                          }
                                                          }





                                                          share|improve this answer













                                                          Below are my findings



                                                              string userID;

                                                          using(SqlConnection conn = new SqlConnection(connectionString))
                                                          {
                                                          string insertQuery = "SELECT UserID FROM Customers WHERE Email = @Email AND
                                                          Password = @Password";
                                                          SqlCommand com = new SqlCommand(insertQuery, conn);
                                                          com.CommandType = CommandType.StoredProcedure;
                                                          com.Parameters.AddWithValue("@Email", tbEmail.Text.ToString().Trim());
                                                          com.Parameters.AddWithValue("@Password", tbPassword.Text.ToString().Trim());
                                                          SqlDataReader reader = com.ExecuteReader();
                                                          while(reader.Read())
                                                          {
                                                          userID = reader["UserID"].ToString();
                                                          }
                                                          }






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Dec 28 '18 at 13:12









                                                          Sravan KumarSravan Kumar

                                                          11




                                                          11






























                                                              draft saved

                                                              draft discarded




















































                                                              Thanks for contributing an answer to Stack Overflow!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function () {
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53958845%2fhow-do-i-convert-an-int-retrieved-from-a-database-to-string%23new-answer', 'question_page');
                                                              }
                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              Angular Downloading a file using contenturl with Basic Authentication

                                                              Olmecas

                                                              Can't read property showImagePicker of undefined in react native iOS