简体   繁体   中英

I can't convert an int and a float with convert.ToString() to string

I have 2 controls in my form,one is an int and the other is a float,I tried to convert with the "Convert.toString()" method but it didn't work and I get all the time a null value this is my code:

string req = "select coef from amortissement where id_amort =@p";
                    textBox4.Text =Convert.ToString(GetRecordsetValue(req, textBox1.Text) as String)

req = "select Plan from amortissement where id_amort =@p";

                    textBox3.Text =Convert.ToString(GetRecordsetValue(req, textBox1.Text) as String);

this is the GetRecordsetValue method:

private Object GetRecordsetValue(string req, string sValParam)
        {
            // ExecuteScalar est optimisée pour récupérer une seule valeur
            SqlCommand cmd = null;
            try
            {
                cmd = new SqlCommand(req, con);
                cmd.Parameters.AddWithValue("@p", sValParam);
                return cmd.ExecuteScalar();
            }
            catch
            {

                return String.Empty;
            }
            finally
            {
                cmd.Dispose();
            }

        }

thanks for Help

The code in GetRecordsetValue returns NULL if your query doesn't find any record matching the WHERE condition. The null value returned is passed back to Convert.ToString() and this throws the exception

  string req = "select coef from amortissement where id_amort =@p";
  object result = GetRecordsetValue(req, textBox1.Text);
  if(result != null)
  {
      textBox4.Text = Convert.ToString(result);
  }
  else
  {
      // and/or a message to the user to correct its inputs.
      textBox4.Text = "";
  }

There is also the problem of the value passed inside the GetRecordsetValue . This value is passed as a string and it is added inside the parameter collection as a string datatype. If the field id_amort is not a string (as it seems from its name) then it is highly probable that your query cannot find the record.

I suggest to create different overloads of GetRecordsetValue. One that takes an integer for example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM