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

2019-08-23 05:52发布

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.

7条回答
Evening l夕情丶
2楼-- · 2019-08-23 06:44

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

查看更多
登录 后发表回答