Juli Andika
Juli Andika

Reputation: 57

How to store data to variable from SQL query in ASP net?

So here is my code. What I'm trying to do store double rate_num value to number variable. But it is still getting an error.

String conn = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
    string query = "select " + rate_from + " from Exchange_rate where ERates_Status = 'Active'";
    SqlConnection sqlcon = new SqlConnection(conn);
    sqlcon.Open();
    SqlCommand cmd = new SqlCommand(query, sqlcon);
    SqlDataReader reader = cmd.ExecuteReader();

    double number = "";

    while (reader.Read())
    {
        double rate_num = reader.GetDouble(0);

        number = rate_num
    }

    number;

    sqlcon.Close();

Upvotes: 0

Views: 889

Answers (1)

Christoph Biegner
Christoph Biegner

Reputation: 56

I have two findings here:

number += rate_num;

I guess you want a sum of the rates. Since number is defined as a string you will get a string as result where all rates are concatenated. Define number as double:

double number = 0;

Second is the line after the while-loop:

number;

What do you want to archive here? This line will not compile neither if number is a string nor double. If this code is part of a method you pssibly want to return the calculated sum of rates. So you could

return number;

But first close your DB connection

Upvotes: 1

Related Questions