我有以下代码需要列出(在ListView中)每种产品,产品类型和已购买该产品的客户数量。我已经尝试过了,但是没有用。
我不确定是否需要创建另一个类,然后定义列表以及需要包含在ListViewItems中的内容。我是C#编码的新手,但是能够使用类似的方法显示数据,但是之前我并不需要进行计算。任何帮助,将不胜感激。如果需要,我可以提供文件(Project和SQL)。
namespace Acme
{
public partial class frmMainForm : Form
{
public frmMainForm()
{
InitializeComponent();
}
//Not sure if the following is correct//
private void DisplaySales()
{
string selectQuery;
selectQuery = "SELECT Products.ProductName, ProductTypes.ProductType, COUNT(Sales.ProductID) as SALES,";
selectQuery = selectQuery + "FROM Products INNER JOIN ProductTypes ON Products.ProductTypeID,";
selectQuery = selectQuery + "ProductTypes.ProductTypeID INNER JOIN, ";
selectQuery = selectQuery + "Sales ON Sales.ProductID = Products.ProductID GROUP BY Products.ProductName ";
selectQuery = selectQuery + "ProductTypes.ProductType, Sales.ProductID";
selectQuery = selectQuery + " " + GlobalVariables.salesSearchCriteria;
SqlConnection conn = ConnectionManager.DatabaseConnection();
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(selectQuery, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//Not sure if I need to create a seperate Class and then define the list (Class - ProductSales??)
//Also need to include ListviewItems ??????
}
if (rdr != null)
rdr.Close();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Unsuccessful" + ex);
}
}
答案 0 :(得分:0)
创建 Product 类,并获取以下示例数据
SqlDataReader reader = command.ExecuteReader();
List<Product> lstProduct = new List<Product>();
if (reader.HasRows)
{
while (reader.Read())
{
Product product = new Product();
product.ProductName = reader.GetString(0);
...
lstProduct.add(product);
}
}
// Do what you want with lstProduct
答案 1 :(得分:0)
是的,您需要创建另一个类。通过该查询获取数据,并将其设置为数据表,然后将数据表分配给Listview。