System.FormatException : 'Input string was not in a correct format.'

DavLn

Member
Joined
Mar 31, 2023
Messages
13
Programming Experience
Beginner
Good evening,

I get an error on this line :

C#:
command.Parameters.AddWithValue("@chambreCat", Convert.ToInt32(cbAdminCat.Text));

I want to be able to convert my character string to INT otherwise I could not insert the value into the database if it is not an integer.

Here is the code for my INSERT INTO query :

C#:
//Ajout des chambres (Admin) / A finir
        private void btnEnregChambresAdmin_Click(object sender, EventArgs e)
        {
            string cs = @"server=localhost;userid=root;password=;database=gestionhotelentretien;charset=utf8";
            MySqlConnection connection = new MySqlConnection(@cs);
            string query = "INSERT INTO utilisateur (CHAMBREID,CHAMBRENOM,CHAMBRECATEGORIE) VALUES(@chambreID,@chambreNom,@chambreCat)";
            MySqlCommand command = new MySqlCommand(query, connection);

            command.Parameters.AddWithValue("@chambreID", txtChNumId.Text);
            command.Parameters.AddWithValue("@chambreNom", txtNameChambres.Text);
            //Finir l'ajout de la catégorie
            command.Parameters.AddWithValue("@chambreCat", Convert.ToInt32(cbAdminCat.Text));

            try
            {
                connection.Open();
                command.ExecuteNonQuery();
                //Console.WriteLine("L'insertion a bien été effectuée !");
                string messageInsertAgent = "L'insertion a bien été effectuée ! ";
                MessageBox.Show(messageInsertAgent);
            }
            catch (MySqlException error)
            {
                Console.WriteLine("Error Generated. Details: " + error.ToString());
                string messageErrorInsertAgent = "La requête contient une ou plusieurs erreurs ! ";
                MessageBox.Show(messageErrorInsertAgent);
            }
            finally
            {
                connection.Close();
            }

        }

And this is the code of my fonction to get the list of categories in String :

C#:
//Fonction récupérant la liste des noms des catégories
        public static List<String> GetLesCategoriesPourAjout()
        {
            List<String> listeDesCategories = new List<String>();
            string query = "SELECT DISTINCT CATID, CATNOM FROM categorie";
            MySqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = query;

            using (MySqlDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    listeDesCategories.Add(rdr.GetString("CATNOM"));
                }
            }
            return listeDesCategories;
        }

I need your help PLS!
 
When I want to display the value of 'cbAdminCat.Text' I get an empty page without any value.

I used this code to try to get the value of 'cbAdminCat' :

C#:
MessageBox.Show((String)cbAdminCat.SelectedValue);
 
Stop what you're doing and learn how to use the debugger right now. There's no reason to be using MessageBox.Show. You should be setting a breakpoint on the line that throws the exception and then using the debugging tools to see the value of the relevant expressions.

That said, you should know what is displayed in the ComboBox already just by looking at it before clicking the Button. If it's not displaying a number, how do you expect to convert what it's displaying to an Int32?

Also, it's seems rather bizarre how you're using that ComboBox. Normally, you would display the list of names to the user for them to select from, then use the corresponding ID in code. That would suggest that you should be using the SelectedValue rather than the Text and it should already be an int so you should be casting rather than converting:
C#:
command.Parameters.AddWithValue("@chambreCat", (int)cbAdminCat.SelectedValue);
 
Sorry I'm still new to C# but even if I cast it I get this error :

System.NullReferenceException: 'Object reference not set to an instance of an object.'
 
Ok, so in the end in my ComboBox I just took the names of the categories and not the id of the categories, that's why I couldn't retrieve any value in my ComboBox
 
oh, there is so much to tell..

So, you should installed Dapper, and your code looks like this:

C#:
        record Cat(int Id, string Desc);

        public static void FillSomeCombo()
        {
            var q = "SELECT CATID as Key, CATNOM as Value FROM categorie";
            var r = conn.Query<Cat>(q);
            cbSomeCombo.DisplayMember = "Desc";
            cbSomeCombo.ValueMember = "Id";
            cbSomeCombo.DataSource = r;
        }

Then when you want to get the selected value in the combo, just

C#:
 var id = (int)sbSomeConvo.SelectedValue;
 
Back
Top Bottom