Convert a textbox value to int when saving the data

andrewmanuja

Well-known member
Joined
May 30, 2019
Messages
75
Programming Experience
Beginner
Hi,

I got an error stating, " Input string was not in a correct format" when trying to insert a window form data in to a SQL database table.

I got a combobox named "cmbCostCentre" and when the user selects a cost centre, the respective Cost Centre ID is retrieved to another textbox named, "txtCostCentreID" on the same form.
Please refer the below code for the respective "Cost Centre ID" retrieval.

C#:
private void cmbCostCentre_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmd = new SqlCommand("SELECT costCentre, costCentreCode FROM tbl_CostCentre WHERE costCentre = @acostCentre ", con);
            cmd.Parameters.AddWithValue("@acostCentre", cmbCostCentre.Text);
            con.Open();
            cmd.ExecuteNonQuery();
            SqlDataReader dr;
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                string costCentreCode = (string)dr["costCentreCode"].ToString();
                txtCostCentreID.Text = costCentreCode;
            }
            con.Close();
        }

My effort is, when the data of the form is saving to the SQL database table, I want to pass both the "Cost Centre" data and the "Cost Centre ID" Data.
I am using the below command to accomplish the task;

C#:
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_UserData (costCentreID,costCentre) VALUES (@acostCentreID,@acostCentre)", con);

cmd.Parameters.Add("@acostCentreID", SqlDbType.Int);
cmd.Parameters["@acostCentreID"].Value = int.Parse(txtCostCentreID.Text);
cmd.Parameters.Add("@acostCentre", SqlDbType.VarChar, 150);
cmd.Parameters["@acostCentre"].Value = cmbCostCentre.Text;

Note
The datatype of the Cost Centre ID is "int" and the Cost Centre is "varchar".

Appreciate your valuable feedback.

Kind regards,

Andrew
 
Last edited by a moderator:
I got an error stating, " Input string was not in a correct format" when trying to insert a window form data in to a SQL database table.
And did you look to see what that input string was, because you haven't told us what it was. I'm guessing that you didn't look and that, if you had, it would be obvious that it wasn't a valid number. The only part of that code that is likely relevant is this:
C#:
int.Parse(txtCostCentreID.Text);
You can't parse a string as an int if it doesn't contain a valid representation of a 32-bit integer.

Once you know what the invalid value is, you can then look into why the value is invalid. If the string is empty, you need to make sure that a value is being set when and where you think it should be. If the value is something else, you need to look at when and where the value is set to see where it's coming from.
 
By the way, that Add method returns the parameter that was added, so this:
C#:
cmd.Parameters.Add("@acostCentreID", SqlDbType.Int);
cmd.Parameters["@acostCentreID"].Value = int.Parse(txtCostCentreID.Text);
cmd.Parameters.Add("@acostCentre", SqlDbType.VarChar, 150);
cmd.Parameters["@acostCentre"].Value = cmbCostCentre.Text;
can be writen more concisely like this:
C#:
cmd.Parameters.Add("@acostCentreID", SqlDbType.Int).Value = int.Parse(txtCostCentreID.Text);
cmd.Parameters.Add("@acostCentre", SqlDbType.VarChar, 150).Value = cmbCostCentre.Text;
 
HI jmcilhinney,

Thanks for the revised "Add" method.

I got the mistake I have done. Yes, as you said, it is in regards to the validity of the integer input.

Thank you very much.

Kind regards,

Andrew
 
Yes, The AddWithValue() replaces the obsolete Add(string, object).

The code in post #1 and #3 are using Add(string, SqlDbType) and Add(string, SqlDbType, int), not the obsolete method.
 
Also, be careful when using int.parse() - If you pass in a value and blindly assume its int, and its actually something like 5.5, you will be hit with a system format exception but instead, I would first prefer int.TryParse() which returns a bool indicating if the value is of type int. Be warned that it fails silently, whereas int.parse() will actually throw an exception if it fails to parse.

If you do use int.parse, consider wrapping that code in a try catch block with an exception of type system format exception and handle the error accordingly. No such try catch blocks are needed for tryparse, however you do need to check the bool state for a value of true if is has parsed.

~Edited out a typo
 
Last edited:
I am to long writing AddWithValue() to recall that the Add(string, object) API is only partially obsolete and not wholly obsolete. I needed to go recheck. Good call Skydiver.

Thanks
 
Back
Top Bottom