C# error : Input string was not in a correct format

38,491

Solution 1

The problem stated by your error message is probably on one of the lines that try to convert the value in the textboxes to a short integer. Without any check, the value typed by your user could be anything but a number and you get this error message (for example, if you user leaves the textboxes empty).

You should try to check if the textboxes content could be converted to a valid short integer using TryParse before attempting to execute the query

int ordered;
if(!int16.TryParse(txtQtyOrdered.Text, out ordered))
{
    MessageBox.Show("Invalid number for Ordered quantity");
    return;
}
int orderID;
if(!int16.TryParse(txtPONumber.Text, out orderID))
{
    MessageBox.Show("Invalid number for OrderId");
    return;
}
int itemID;
if(!int16.TryParse(txtItemNo.Text, out itemID))
{
    MessageBox.Show("Invalid number for ItemID");
    return;
}

At this point you could execute your calculation using the converted short integers and then write your query in this way (adding a space before the AND)

  com.CommandText =
        "UPDATE PODetail SET BalanceQty="+ newbal.ToString() +
        " WHERE OrderID=" + orderID.ToString() + 
        " AND ItemID=" + itemID.ToString();

But the string concatenation of query text and user input is never advised as a good practice (in your case is harmless because if the conversion is successful you don't have to worry about Sql Injection, but don't take the habit to do it).
So the perfect way to write this query is through the use of a parametrized query

  com.CommandText =
        "UPDATE PODetail SET BalanceQty=@newbal " +
        " WHERE OrderID=@orderID " + 
        " AND ItemID= @itemID"

  com.Parameters.AddWithValue("@newbal", newBal);
  com.Parameters.AddWithValue("@orderID", orderID);
  com.Parameters.AddWithValue("@itemID", itemID);
  com.ExecuteNonQuery();

As a good article on Parameterized query and why to use them, I suggest to read these old words from Jeff Atwood

Solution 2

I'd recommend making changes according to the following code review suggestions based on the code (listed in order of value (cost/benefit of "fixing")):

  1. This method, which is accessing a database should not be reading controls to get its values. Instead there should be an event handler, such as a button click, that parses the values of other controls, using TryParse, as gregjer answered. By segregating the UI and Data code, the data access layer is easier to test and by parsing at the surface (the UI layer) exceptions dealing with bad user input will be caught as soon as possible.
  2. Dynamic SQL via strings in the database or in the data access layer w/i .NET is open to SQL injection. You are resolving that issue by parsing the text, so awesome job by you. BUT, this was already handled by the .NET team by providing parameterized commands. Refer to the MSDN SqlCommand.Parameters or see here for a brief, including how a consuming developer groks this topic: When should "SqlDbType" and "size" be used when adding SqlCommand Parameters?
  3. Variable naming. Instead of Qty, standard .NET naming conventions would call for quantity, camelCased since it is a parameter and the full human language name, not a shorthand or abbreviation, especially for publicly visible bits. IntelliSense makes long variable names not a problem. Since .NET is unwieldy using just Notepad, it should be assumed that other developers are using an IDE such as VisualStudio or SharpDevelop, so use meaningful names.
  4. Stored procedures should be used. Every time this SQL is executed, SQL Server needs to check its command cache minimally, but if the command has been flushed from cache, the SQL command needs to be interpreted and encached (put into cache). This as well as the fact that using a stored procedure requires "shipping" less bytes on every call to the database.

Solution 3

You need to put a space before your "AND" and that you are trying to convert a string to an integer that isn't an integer.

Share:
38,491
user2874217
Author by

user2874217

Updated on June 11, 2020

Comments

  • user2874217
    user2874217 almost 4 years

    I was getting this error: "Input string was not in a correct format."

    Here is my Code:

        private void UpdatePOdetailBalance(int Qty)
        {
            int newbal;
    
            SqlCommand com = new SqlCommand();
    
            com.Connection = cn;
    
            newbal = Convert.ToInt16(txtQtyOrdered.Text) - Qty;
            com.CommandText =
                "UPDATE PODetail SET BalanceQty="+ newbal +" WHERE OrderID=" +
                 Convert.ToInt16(txtPONumber.Text) + "AND ItemID=" +
                 Convert.ToInt16(txtItemNo.Text);
    
    
            com.ExecuteNonQuery();
    
        }
    
        private void btnOK_Click(object sender, EventArgs e)
        {
    
                UpdatePOdetailBalance(Convert.ToInt16(txtQuantity.Text));
    
        }
    

    I want to compute the newbal which is equal to txtQtyOrdered minus Qty but i'm getting this error please help me with this. Thanks.