使用不同的查询填充datagrid列

时间:2016-04-16 22:09:59

标签: c#

我有以下表格

category {name}
purchase {pdtname, amount, catName}
sales {pdtname, amount, catName}

我想添加一个数据网格,并显示类别表中的类别名称 我已经使用此代码

完成了这项工作
            SqlDataAdapter da = new SqlDataAdapter("SELECT name from cate", ConnectionInfo.con);

            DataTable dt = new DataTable();

            da.Fill(dt);
            dataGridView1.DataSource = dt;
            this.dataGridView1.Columns[0].HeaderText = "الفئة"; 

它工作正常,并显示类别。

但我也想在每个类别名称旁边显示总费用和总销售额

我尝试编写此代码,但我知道它不完整或错误

     for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                double exp2 = 0, rev2 = 0;
                SqlCommand cmd2 = new SqlCommand("select amount from purchase where year=@year and month=@month and cat=@cat ", ConnectionInfo.con);

                cmd2.Parameters.AddWithValue("@month", comboBox2.Text);
                cmd2.Parameters.AddWithValue("@year", comboBox3.Text);
                cmd2.Parameters.AddWithValue("@cat", dataGridView1.Rows[i].Cells[0].Value);

                SqlDataReader dr2 = cmd2.ExecuteReader();
                while (dr2.Read())
                {
                    exp2 += Convert.ToDouble(dr2[0]);
                    MessageBox.Show(exp2 + "");
                }
                dr2.Close();

            }
            dr3.Close();

        }
        catch (Exception ex)
        {
            MessageBox.Show("error " + ex);
        }

        finally
        {
            ConnectionInfo.con.Close();
        }

如何在datagrid列中输入要打印的数字 所以对于每个类别,我都可以查看总费用

1 个答案:

答案 0 :(得分:1)

SELECT name, (SELECT SUM(amount) from purchase where year=@year and month=@month and catName=c.Name) from cate c