我试图将我的SQL Server数据库中某些列的总结显示为Winforms textboxes
,但我遇到了困难而且我不知道更多。
我database
中的表格如下:
我的C#代码:
if (combobox1.SelectedText != null)
{
string CS = (@"Data )
SqlConnection con = new SqlConnection(CS);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandText = ("[dbo].[spSalesAnalyse]");
sqlCmd.CommandType = CommandType.StoredProcedure;
cbAnalyse.SelectedValue.ToString());
SqlDataReader myReader;
try
{
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(sqlCmd);
// Save the results in the DT. Call the adapter statement and fill it in the DT
DataTable dt = new DataTable();
adapter.Fill(dt);
//Fill textBoxes with data in DT
textBox1.Text = dt.Rows[0].Field<string>("North");
textBox2.Text = dt.Rows[1].Field<string>("East");
textBox3.Text = dt.Rows[2].Field<string>("West");
....
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
else
MessageBox.Show("Error");
我的期望:
问题:如果我调试到这一行adapter.Fill(dt)
,我确实看到记录但是他们没有到达我的textBoxes。当debugg到达textBoxes级别时,它们是空的
希望我表达得很好
答案 0 :(得分:1)
看起来您正在尝试一次获取一个文本框值。您可以使用SQL中的GROUP BY
子句来获取数据。
SELECT
Country,
Region,
SUM([Sales1]) AS [First Sales],
SUM([Sales2]) AS [Sec Sales],
SUM([Sales3]) AS [Third Sales]
FROM
[dbo].[tblSales]
GROUP BY Country, Region
单个查询将返回您的所有结果。您可以在DataSet
中获取此结果,然后通过从DataSet中获取值来设置相应文本框的值。
//Use query string as show above
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
现在您的DataSet中有记录,您可以填充文本框。
DataRow dataRow = dataset.Tables[0].Select("Country = 'Italy' AND Region = 'North'").FirstOrDefault();
if (dataRow != null) {
textbox1.Text = dataRow["First Sales"].ToString();
}
答案 1 :(得分:0)
听起来像GROUP BY
的情况编辑回答OP的评论
SELECT region, country
, SUM ( sales1 ) as [First Sales]
, SUM ( sales2 ) as [Second Sales]
, SUM ( sales3 ) as [Third Sales]
FROM tblSales
GROUP BY country, region