简体   繁体   English

C#datagridview列出

[英]C# datagridview to list

I am currently developing an point of sale system so i have a datagridview for the pay form and there are data loaded from the database that has the data of the products, but i need to calculate the total of the sum of the products but also i have a quantity column which i need. 我目前正在开发一个销售点系统,因此我有一个用于付款表单的datagridview,并且从数据库中加载了包含产品数据的数据,但是我需要计算产品总和,但我有我需要的数量列。 What do you suggest ? 你有什么建议? Should i convert the elements from the datagridview to list ? 我应该将datagridview中的元素转换为list吗?

Here is what i have tried: 这是我尝试过的:

 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();
        }
    }

You could achieve this by looping on your rows and calculating the sum: 您可以通过循环行并计算总和来实现此目的:

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;
}

You could add a column of Qty * Price. 您可以添加“数量*价格”列。 You only have to do this once. 您只需要执行一次。

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);

Then you can do a Compute: 然后,您可以进行计算:

decimal computedTotal = ((Data.DataTable)dataGridView1.DataSource).Compute("Sum(ItemTotal)");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM