【发布时间】:2014-02-27 13:05:36
【问题描述】:
所以我在 foreach 循环中抓取每一行并计算它的价格。我设法做到了,但我似乎无法弄清楚如何将所有计算的行存储到一个变量中并将 1 个计算的答案插入数据库。
private void btnSubmitConsultation_Click(object sender, EventArgs e)
{
string cMedication = string.Empty;
string cQuantity = string.Empty;
string cAppointment = string.Empty;
foreach (DataGridViewRow row in this.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);
}
}
}
private void calculateTotal(string cMedication, string cQuantity, string cAppointment)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["HConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnectionString);
string insertPayment = "INSERT INTO PAYMENT (amount, appointmentID) " +
"VALUES (@insertAmount, @insertAppointment)";
using (SqlConnection connection = new SqlConnection(strConnectionString))
{
using (SqlCommand cmdPayment = new SqlCommand(insertPayment, connection))
{
string strPrice = "SELECT medicationPrice FROM MEDICATION WHERE medicationName= @getName";
SqlCommand cmdPrice = new SqlCommand(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;
for (int i = 0; i < dataPrescription.Rows.Count; i++)
{
double total = result * i;
string answer = result.ToString();
MessageBox.Show(answer);
cmdPayment.Parameters.AddWithValue("@insertAmount", answer);
}
}
readPrice.Close();
con.Close();
cmdPayment.Parameters.AddWithValue("@insertAppointment", txtAppointmentID.Text);
connection.Open();
cmdPayment.ExecuteNonQuery();
connection.Close();
}
}
}
【问题讨论】:
标签: c# sql winforms for-loop datagridview