String format error input string was not in a correct format

I tried to make a code to insert all my data from a grid into a table. In the grid I display what I need, it's not the problem, or it does not give an error
  • Remove From My Forums
  • Question

  • I tried to make a code to insert all my data from a grid into a table. In the grid I display what I need, it’s not the problem, or it does not give an error

    Displays this error:

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

    My table: 

    CREATE TABLE [dbo].[concediati] (    [Id]       INT          IDENTITY (1, 1) NOT NULL,    [nume]     VARCHAR (50) NULL,    [prenume]  VARCHAR (50) NULL,    [idclient] INT          NULL,    [idrent]   INT          NULL,    [idcar]    INT          NULL,    PRIMARY KEY CLUSTERED ([Id] ASC));

     string StrQuery;
                try
                {
                    using (SqlConnection conn = new SqlConnection(stringcon))
                    {
                        using (SqlCommand comm = new SqlCommand())
                        {
                            comm.Connection = conn;
                            conn.Open();
                            for (int i = 1; i < bunifuCustomDataGrid2.Rows.Count; i++)
                            {

                               

                                StrQuery = @»INSERT INTO concediati(nume,prenume,idcar,idrent,idclient) VALUES (@name,@lastname,@car,@rent,@client)»;
                                comm.Parameters.AddWithValue(«@name», Convert.ToString(bunifuCustomDataGrid2.Rows[i].Cells[«firstname»].ToString()));
                                comm.Parameters.AddWithValue(«@lastname», Convert.ToString(bunifuCustomDataGrid2.Rows[i].Cells[«lastname»].ToString()));
                                comm.Parameters.AddWithValue(«@car», Convert.ToInt32(bunifuCustomDataGrid2.Rows[i].Cells[«CARS»].ToString()));
                                comm.Parameters.AddWithValue(«@rent», Convert.ToInt32(bunifuCustomDataGrid2.Rows[i].Cells[«RENT»].ToString()));
                                comm.Parameters.AddWithValue(«@client», Convert.ToInt32(bunifuCustomDataGrid2.Rows[i].Cells[«CLIENT»].ToString()));

                                

                                comm.CommandText = StrQuery;
                                comm.ExecuteNonQuery();
                            }
                        }
                    }

    • Edited by

      Sunday, March 31, 2019 2:23 PM

Answers

  • Hi lulianG06,

    According to your description, I make a simple example to reproduce the same error as yours.

    Please check the value you insert into the database matches the data type you defined in database.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
    MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by
      IulianG06
      Tuesday, April 2, 2019 7:02 PM

Input string was not in a correct format errorThe input string was not in a correct format error might occur when you try to convert a non-numeric string from the input into an int. Moreover, you’ll get the said error while storing the input values that are larger than the range of the int data type as int. This post explains the causes stated above to give you clarity before you read about the solutions.

Continue reading to see how to solve the error and get your program back on track.

Why the Input String Was Not in a Correct Format Error Occur?

The given error occurs when you attempt to convert non-numeric data into an int. Also, exceeding the limit of the int data type to store larger values will give you the same error. Here are the detailed explanations of the causes:

– Converting the Non-numeric Data in Text Boxes Into Int

Are you working on a Windows Form and getting the above error? Well, the issue might be with converting the data of the empty text boxes when the form loads for the first time. So, here the erroneous code might be the one that attempts to convert an empty string from the text box into an int.

This line of code might throw the mentioned error when called inside the constructor:

lucky_number = Int32.Parse(luckyTextBox.Text);

– You Are Using Int With Input Values Larger than the Int Range

If the input provided by the user is larger than the range of int data type and you attempt to store the same in an int column, then the stated error occurs.

How To Fix the Format Error Found With the Strings?

You can fix the given error by putting into use the below solutions as per your need:

– Use the Int.TryParse() Method

As the text boxes are always empty when the form is loaded for the first time, you should use the Int.TryParse() method instead of the Int32.Parse() method. It will ensure that the error isn’t thrown even if the empty strings are attempted to be converted.

Replace the above line of code with the following:

lucky_number = Int.TryParse(luckyTextBox.Text);

– Use Varchar Instead of Int To Fix the Input String Was Not in a Correct Format Error

You should use the varchar data type instead of int to store any values that are larger than the range of int. It will most probably solve the error.

FAQ

Here you’ll find some additional information that will help you in your coding routine:

– What Is an ‘Input’ String?

An ‘input’ string refers to the data passed to a computer through a peripheral device such as a keyboard. A good example of this can be the data that you fill in the text boxes of an online form.

– How To Ensure That the ‘Input’ String Matches a Particular Format?

You can use a variety of methods including the regular expressions and loops to check if the given input string matches a particular format. Indeed, the regular expressions offer a quick and easy way to ensure the correctness of the string format. Moreover, using the loops can be helpful when you want to check each character of the string individually. So, it depends on your program requirements and the logic that you are trying to implement.

– How To Get Rid of Number Format Exception in Java?

You can resolve the number format exception in Java by checking if the string that you are trying to parse contains a numeric value. It is because the given exception occurs when you convert a string that doesn’t fulfill the requirements of an integer data type. Now, the name of the stated exception might be clear to you as well.

Conclusion

You don’t need to be worried anymore regarding the error discussed in this article. Indeed, it can be solved easily if you implement the stated solutions. Please look here for one-liner solutions:

  • Input string was not in a correct format error occurs when you convert non-numeric data into an int or exceed the limit of the int data type.
  • You should use Int.TryParse instead of Int32.Parse method to get rid of the said error
  • You should store large numeric values in a column with a varchar data type

How to fix input string was not in a correct formatNever forget to match the destination data type with input data to avoid such kind of errors in the future.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

Ive made a registration form(using asp.net and C#) with some attributes like username, password,date of birth,phone no,address, gender, postal code etc. There’s no error in the code.
But When I run my web site and fill in the details, and press the OK button, I get an error:»Input string was not in a correct format.»
Plz help me!

the code is:

private void ExecuteInsert(string Username, string Password, string Confirmpassword, string EmailID, string Firstname, string Lastname, string Address, string City,string State, string Country, string Postalcode,string PhoneNo, string gender, string DOB)
        {
       
            SqlConnection con = new SqlConnection(" Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Online job portal\App_Data\database.mdf;Integrated Security=True;User Instance=True");

            string sql = "INSERT INTO ojb1(Username,Password,ConfirmPassword,EmailID,Firstname,Lastname,Address,City,State,Country,Postalcode,PhoneNo,Gender,DOB) VALUES" + "(@Username,@Password,@ConfirmPassword,@EmailID,@Firstname,@Lastname,@Address,@City,@State,@Country,@Postalcode,@PhoneNo,@Gender,@DOB)";

            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand(sql, con);
                SqlParameter[] param = new SqlParameter[14];

                param[0] = new SqlParameter("@Username", SqlDbType.VarChar, 50);
                param[1] = new SqlParameter("@Password", SqlDbType.VarChar, 50);
                param[2] = new SqlParameter("@ConfirmPassword", SqlDbType.VarChar, 50);
                param[3] = new SqlParameter("@EmailID", SqlDbType.VarChar, 50);
                param[4] = new SqlParameter("Firstname", SqlDbType.VarChar, 50);
                param[5] = new SqlParameter("Lastname", SqlDbType.VarChar, 50);
                param[6] = new SqlParameter("Address", SqlDbType.VarChar, 50);
                param[7] = new SqlParameter("City", SqlDbType.VarChar, 50);
                param[8] = new SqlParameter("State", SqlDbType.VarChar, 50);
                param[9] = new SqlParameter("Country", SqlDbType.VarChar, 50);
                param[10] = new SqlParameter("Postalcode", SqlDbType.Int, 100);
                param[11] = new SqlParameter("PhoneNo", SqlDbType.Int,100);
                param[12] = new SqlParameter("Gender", SqlDbType.Char, 10);
                param[13] = new SqlParameter("DOB", SqlDbType.VarChar, 50);


                param[0].Value = Username;
                param[1].Value = Password;
                param[2].Value = Confirmpassword;
                param[3].Value = EmailID;
                param[4].Value = Firstname;
                param[5].Value = Lastname;
                param[6].Value = Address;
                param[7].Value = City;
                param[8].Value = State;
                param[9].Value = Country;
                param[10].Value = Postalcode;
                param[11].Value = PhoneNo;
                param[12].Value = gender;
                param[13].Value = DOB;

                for (int i = 0; i < param.Length; i++)
                {
                    cmd.Parameters.Add(param[i]);
                }
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
            }

            catch (SqlException ex)
            {
                string msg = "Insert Error";
                msg += ex.Message;
                throw new Exception(msg);

            }
            finally
            {
                con.Close();
            }
           
        }
        
    
     
    
 public static void ClearControls(Control Parent)

    {

        if (Parent is TextBox)

        { (Parent as TextBox).Text = string.Empty; }

        else

        {

            foreach (Control c in Parent.Controls)

                ClearControls(c);

        }

    }
    protected void Next1_Click(object sender, EventArgs e)
    {
        if (password.Text == confirmpass.Text)
        {
            ExecuteInsert(username.Text, password.Text, confirmpass.Text, EmailID.Text, firstname.Text, Lastname.Text, Address.Text, City.Text, State.Text, Country.Text,Postalcode.Text,Phoneno.Text,Gender.SelectedItem.Text,DOB.Text);
            Response.Write("Record was successfully added");
            ClearControls(Page);
        }
        else
        {
            Response.Write("password did not match");
            password.Focus();
        }
    }

Problem

FormatException
Input string was not in a correct format.

System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at Thycotic.webapp.Web.AdminSecretPolicyEdit.<>c__DisplayClass96_0.b__2(String p) at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at Thycotic.webapp.Web.AdminSecretPolicyEdit.GetUpdatesToItems(List`1& updatedItems, List`1& groupIds, List`1 oldGroupIds, List`1& sshCommandMenuPermissions, List`1 oldsshCommandMenuPermissions) at Thycotic.webapp.Web.AdminSecretPolicyEdit.HiddenSaveButton_Clicked(Object sender, EventArgs e) at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) User: IIS APPPOOLSecretServer

image 5107

image 5108

Cause

This is a known issue when using Chrome browser that is not localized to the English language.

Environment

Secret Server Version 10.7 or prior

Resolving The Problem

This issue is fixed in the 10.8.000000 release.

To resolve, either upgrade to the 10.8 release, or perform the following workaround:

Switch your Browser to use English

(in Chrome visit chrome://settings/languages and add English and move this to the top of the list)

Then Create or Edit the policy and save.

Then Switch back to your chosen language

Document Location

Worldwide

[{«Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Product»:{«code»:»SSWHLP»,»label»:»IBM Security Secret Server»},»ARM Category»:[{«code»:»a8m0z0000001hkjAAA»,»label»:»Secret Server->POLICY»}],»ARM Case Number»:»TS003931243″,»Platform»:[{«code»:»PF025″,»label»:»Platform Independent»}],»Version»:»10.7.0″,»Line of Business»:{«code»:»LOB24″,»label»:»Security Software»}}]

Понравилась статья? Поделить с друзьями:
  • String error 102 hikvision
  • String descriptor 0 read error 71
  • Strict nat destiny 2 как исправить pc
  • Stopped upon error after linx
  • Stress web fatal error in unknown on line 0