Quantcast
Channel: Windows Forms General forum
Viewing all articles
Browse latest Browse all 12583

C#: How do you compute each row of foreach double value to compute into a SINGLE value and insert ir to DB?

$
0
0

Right now I have this logic behind my code:

INSERTINTO PAYMENT (amount, appointmentID)VALUES(@amount1,@app1),(@amount2,@app2),(@amount3,@app3),
... and so on depending on how much medication I select

Let's say the value of @amount1 is 10, @amount2 is 15 and @amount3 is 20

How do i compute the TOTAL value of @amount1, @amount2 and @amount 3 into a total sum and submit it into the database as a total value of 45 in this manner: (@amount1, @app1) / 1 ROW only instead of 3 ROWS?  How do I approach this kind of logic?

This is what I have for my button click code:

string cMedication =string.Empty;string cQuantity =string.Empty;string cAppointment =string.Empty;foreach(DataGridViewRow row inthis.dataPrescription.Rows){
    cMedication = row.Cells[0].Value.ToString();
    cQuantity = row.Cells[1].Value.ToString();
    cAppointment = txtAppointmentID.Text;if(cAppointment =="NO APPOINTMENT HAS BEEN MADE"){MessageBox.Show("Please make an appointment first at the Nurse counter","WARNING");}else{this.calculateTotal(cMedication, cQuantity, cAppointment);}}

and this is my calculateTotal function:

privatevoid calculateTotal(string cMedication,string cQuantity,string cAppointment){string strConnectionString =ConfigurationManager.ConnectionStrings["HConnection"].ConnectionString;SqlConnection con =newSqlConnection(strConnectionString);string insertPayment ="INSERT INTO PAYMENT (amount, appointmentID) "+"VALUES (@insertAmount, @insertAppointment)";using(SqlConnection connection =newSqlConnection(strConnectionString)){using(SqlCommand cmdPayment =newSqlCommand(insertPayment, connection)){string strPrice ="SELECT medicationPrice FROM MEDICATION WHERE medicationName= @getName";SqlCommand cmdPrice =newSqlCommand(strPrice, con);
            cmdPrice.Parameters.AddWithValue("@getName", cMedication);

            con.Open();SqlDataReader readPrice = cmdPrice.ExecuteReader();if(readPrice.Read()){string getPrice = readPrice["medicationPrice"].ToString();double doublePrice =Convert.ToDouble(getPrice);double doubleQuantity =Convert.ToDouble(cQuantity);double result = doublePrice * doubleQuantity;string answer = result.ToString();
                cmdPayment.Parameters.AddWithValue("@insertAmount", answer);}

            readPrice.Close();
            con.Close();

            cmdPayment.Parameters.AddWithValue("@insertAppointment", txtAppointmentID.Text);

            connection.Open();
            cmdPayment.ExecuteNonQuery();
            connection.Close();}}}

Viewing all articles
Browse latest Browse all 12583

Trending Articles