dbz
dbz

Reputation: 284

C# from numeric to double

we have a value in our database that is numeric we take through the database and then we want to insert it to another value but we want it to be converted to DOUBLE from Numeric

So any ideas how can we convert our Numeric variable to double ?

edit

Database = Microsoft SQL Server Database File (SqlClient) (.mdf)

double point = 0;


cn.Open();
point = Convert.ToDouble("select bounty from provider where sirname = '" + globals2.stringena + "' ");
cn.close();

bounty = Numeric(18,2)

so want to pass this value to my point variable.

The error i get is

Input string was not in a correct format.

Upvotes: 1

Views: 4749

Answers (1)

Elior
Elior

Reputation: 3266

string query = "select bounty from provider where sirname = @name";
double numericToDouble = 0;
using (SqlConnection con = new SqlConnection(YourDB.ConnectionString)
{
    using(SqlCommand cmd = new SqlCommand(query,con))
    {
        cmd.Parameters.AddWithValue(@name,"nameYouNeed");
        try{
          con.Open();
          SqlDataReader reader = cmd.ExecuteReader();
          if (reader.Read())
             numericToDouble = Convert.ToDouble32(reader[0].ToString());
          con.Close();
        }
        catch(SqlError someError)
        {
           MessageBox.Show(someError.Message);
        }
    } 
}

Note: the @name is a parameter that we need to pass to the query at runtime. so I created an sql command that uses the query and connect to the DB. when the new command is create it passes the value of @name, if you see the line "cmd.parameters...." after that it reads from the DB, and check if it succeeded to read something, if so it convert the value to string and then to double. I assumed that the numeric field is the first column in your table. If it's not you can change the code FROM:

numericToDouble = Convert.ToDouble32(reader[0].ToString());

TO:

numericToDouble = Convert.ToDouble32(reader["NameOfTheNumericField"].ToString());

Hope this will help you..

Upvotes: 2

Related Questions