0

I'm trying to retrieve a data from a table and subtract it to another variable, but I'm getting this error Input string was not in a correct format. Here is my code:

    SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ConnectionString);
    DataTable dt = new DataTable();
    con1.Open();
    SqlDataReader myReader = null;
    SqlCommand myCommand = new SqlCommand("SELECT Cash from Sales where SalesID='" + GridView2.Rows[0].Cells[0].Text+"'", con1);

    myReader = myCommand.ExecuteReader();
    while (myReader.Read())
    {
        TextBox3.Text = myReader["Cash"].ToString();
        TextBox4.Text = (Int32.Parse(TextBox3.Text.ToString()) - Total).ToString();
    }
    con1.Close();

I got the error from this line:

TextBox4.Text = (Int32.Parse(TextBox3.Text.ToString()) - Total).ToString();

It seems that I have an issue in subtracting those variables. Any help would be appreciated. Thanks!

Joe Marie
  • 346
  • 2
  • 8
  • 22
  • Are you sure you're getting a value back for myReader["Cash"]? You could comment out that the line for TextBox4.Text and see what value gets in TextBox3 or just step through your debugger. – sjramsay Oct 04 '14 at 19:29

2 Answers2

0

If you are in a position to have direct access to the original field, don't go through extra effort to try to convert it from another object. Use the reader directly and don't try to get TextBox3.Text.

I'm guessing though that your problem is going to be that Cash has something in it that won't work for conversion. For example, a $. Int is also a poor datatype for working with money since you can't have decimal points, int is whole numbers only.

If Cash contains a $, you could try the following.

if(myReader.Read())
{
   // changed the while loop to an if. While loop is useless because if more than 1 row is returned
// then it just keeps setting the same textboxes over and over.

// check to make sure Cash isn't null
    if(!myReader.IsDbNull(myReader.GetOrdinal("Cash")))
    {
          TextBox3.Text = myReader["Cash"].ToString();
          // setup a temporary variable to hold the output of Cash in
          decimal cash = 0;
          // remove trailing whitespace and replace a currency with no space and attempt to convert
          if(decimal.TryParse(myReader["Cash"].ToString().Trim().Replace("$",""),out cash))
          { 
              // set TextBox4 only if the cash really is a value we can work with and subtract Total from 
              TextBox4.Text = (cash - (decimal)Total).ToString();
          }
    }
}
Mark Fitzpatrick
  • 1,624
  • 1
  • 11
  • 8
0

The error is occurring when you try to parse. One of the variables are likely null or empty. Make sure all values are set as type string.

cesaraviles
  • 154
  • 1
  • 4