0

I am using C# and SQL Server.

I have to retrieve the prices of particular products from a table and make use of these values later for computation.

For eg.

I use the following query and store it in a string.

string str = " select cat_price from category where cat_itemID= 'A001'" ;

Now I need this particular value retrieved here to be stored in a variable for further computation

for eg.

int price_amount;

and I need to use mathematical operations. How do I do this?

2
  • Are you asking how to retrieve data from a DB? Or is this a type casting problem(i.e. converting from a string to an int)? Commented Apr 22, 2011 at 3:19
  • You need to perform math operations on the price within the query ? Commented Apr 22, 2011 at 3:24

2 Answers 2

3

Use the ExecuteScalar method of a SqlCommand to get the first value:

using (SqlConnection cn = new SqlConnection(...))
{
    using (SqlCommand cmd = new SqlCommand(cn, "select cat_price from category where cat_itemID= 'A001'"))
    {
        //Execute the query and just get the first result.
        int value = (int)cmd.ExecuteScalar();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your input.I was able to solve the problem by parsing the string. decimal num = decimal.Parse(str);
0

You can use SQLDbConnection and ExecuteScaler to get get this out of the DB if that is your question. Below is a link to do this.

http://www.codeproject.com/KB/database/sql_in_csharp.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.