Visual Studio C# Error: Input string was not in correct format

VAer-4038 771 Reputation points
2021-01-01T18:02:15.63+00:00

The error shows up when running into " int count = Convert.ToInt32(cmd.ExecuteScalar())", Data Type for Access UserID is short text. What goes wrong?

Thanks.

52710-input-string.jpg

        private void btnConnect_Click(object sender, EventArgs e)  
        {  
              
            OdbcConnection Cn = new OdbcConnection(GlobalVariables.DatabaseConnectionString);  
  
            Cn.Open();  
  
            string select = "SELECT * from TUser WHERE UserID ='" + Environment.UserName + "'";  
   
  
            using (OdbcCommand cmd = new OdbcCommand(select, Cn))  
                {  
                  
                int count = Convert.ToInt32(cmd.ExecuteScalar());  
                    if (count > 0)  
                    {  
                        MessageBox.Show("Existed!");  
                    }  
                    else  
                    {  
  
                        MessageBox.Show("No existed");  
                    }  
                //}  
            }  
  
  
        }  
  
Developer technologies Visual Studio Other
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-01-01T18:08:29.36+00:00

    To make it work with minimal changes, try *“select ****COUNT(*)*** from…”, however this is not the only known approach.


1 additional answer

Sort by: Most helpful
  1. Sergio Parra Guerra 1 Reputation point MVP Volunteer Moderator
    2021-01-01T18:11:35.423+00:00

    Hi! ExecuteScalar returns an object.
    Sometimes it can return a DBNull representing a non-existent value, which is not casteable to Int32.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.