MarcIT MarcIT - 19 days ago 6
C# Question

How can I use a SQL value in a formula

I have a C# winform app, that contains a formula. The formula works ok but depending on the id from a SQL table the numbers in the formula can change.

How can I accomplish this?

The code I have is:

private void button1_Click(object sender, EventArgs e)
{
decimal ufa1;
decimal aav1;
decimal uft1;

ufa1 = uft1 * aav1 * VALUE FROM SQL;
}


I have a previous query that gets the value I want but I can't get it integrated in the formula.

The code to get the id is:

con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select prumos from dbo.modelos where id = '"+id+"'";
SqlDataReader dr = cmd.ExecuteReader();

Answer
private void button1_Click(object sender, EventArgs e) 
{
    decimal ufa1;
    decimal aav1; 
    decimal uft1;

    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select prumos from dbo.modelos where id = '"+id+"'";
    //SqlDataReader dr = cmd.ExecuteReader();
    //decimal ValueFromDB = (decimal)cmd.ExecuteScalar();
    decimal ValueFromDB = Decimal.Parse(cmd.ExecuteScalar().ToString());


    ufa1 = uft1 * aav1 * ValueFromDB ;  
}


Or even better:

    private void button1_Click(object sender, EventArgs e)
    {
        decimal ufa1;
        decimal aav1;
        decimal uft1;
        decimal ValueFromDB;

        using (SqlCommand cmd = new SqlCommand("select prumos from dbo.modelos where id = @ID", con))
        {
            cmd.Parameters.Add(new SqlParameter("ID", id));
            ValueFromDB = Decimal.Parse(cmd.ExecuteScalar().ToString());

        }
        ufa1 = uft1 * aav1 * ValueFromDB;
    }