![](/img/trans.png)
[英]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.