[英]C# datagridview to list
我目前正在開發一個銷售點系統,因此我有一個用於付款表單的datagridview,並且從數據庫中加載了包含產品數據的數據,但是我需要計算產品總和,但我有我需要的數量列。 你有什么建議? 我應該將datagridview中的元素轉換為list嗎?
這是我嘗試過的:
private void textBox1_TextChanged(object sender, EventArgs e)
{
MySqlConnection connection = Connection.prevzemiKonekcija();
connection.Open();
try {
MySqlCommand command;
MySqlDataAdapter adapter;
DataTable tabela;
string query = "SELECT barcode,ProductName, SellPrice FROM artikli WHERE barcode like '%" + txtBarajKod.Text + "%'";
command = new MySqlCommand(query, connection);
adapter = new MySqlDataAdapter(command);
tabela = new DataTable();
dataGridView1.DataSource = tabela;
adapter.Fill(tabela);
dataGridView1.Columns[1].HeaderText = "Шифра";
dataGridView1.Columns[2].HeaderText = "Назив";
dataGridView1.Columns[3].HeaderText = "Цена";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally {
connection.Close();
}
}
您可以通過循環行並計算總和來實現此目的:
decimal total = 0;
foreach (var row in dataGridView1.Rows)
{
// 1 is the index of your Quantity column
var qty = Convert.ToInt32(row.Cells[1].Value);
// 2 is the index of your Price column
var price = Convert.ToDecimal(row.Cells[2].Value);
total += qty * price;
}
您可以添加“數量*價格”列。 您只需要執行一次。
DataColumn subTotalColumn = new DataColumn();
subTotalColumn.DataType = System.Type.GetType("System.Decimal");
subTotalColumn.ColumnName = "ItemTotal";
subTotalColumn.Expression = "Qty * Price";
((Data.DataTable)dataGridView1.DataSource).Columns.Add(subTotalColumn);
然后,您可以進行計算:
decimal computedTotal = ((Data.DataTable)dataGridView1.DataSource).Compute("Sum(ItemTotal)");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.