[英]How to update data in a sql server database with values from textboxes when only some of the textboxes are empty and some are filled?
[英]How to display/ fire data (sum column values) from SQL Server database in C# WinForm textBoxes
我試圖將來自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級別時,它們為空
希望我表現得很好
看起來您正在嘗試一次獲取一個文本框值。 您可以在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);
現在,您在數據集中具有記錄,您可以填充文本框。
DataRow dataRow = dataset.Tables[0].Select("Country = 'Italy' AND Region = 'North'").FirstOrDefault();
if (dataRow != null) {
textbox1.Text = dataRow["First Sales"].ToString();
}
聽起來像是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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.