C# 将列的总和反映到WinForm上的标签
我想将列的总和反映到WinForm上的标签上。我不知道这个代码有什么问题:C# 将列的总和反映到WinForm上的标签,c#,sql-server,winforms,C#,Sql Server,Winforms,我想将列的总和反映到WinForm上的标签上。我不知道这个代码有什么问题: private void btnT_Click(object sender, EventArgs e) { SqlConnection cn = new SqlConnection("data source = TURKY-PC ; initial catalog = coffeeshopDB ; integrated security = true ; "); SqlCommand cm
private void btnT_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("data source = TURKY-PC ; initial
catalog = coffeeshopDB ; integrated security = true ; ");
SqlCommand cmd;
SqlDataReader dr;
cmd = new SqlCommand("select SUM (cost) from billTB", cn);
cn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
btnT.Text = dr["cost"].ToString();
}
dr.Close();
cn.Close();
}
出现的错误异常是:
System.IndexOutOfRangeException:“cost”
如果要按名称引用列,则必须命名总和的结果。在这种情况下,您也不需要循环,因为您知道只有一行
private void btnT_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("data source = TURKY-PC ; initial
catalog = coffeeshopDB ; integrated security = true ; ");
SqlCommand cmd;
SqlDataReader dr;
cmd = new SqlCommand("select SUM (cost) as TotalCost from billTB", cn);
cn.Open();
dr = cmd.ExecuteReader();
dr.Read();
btnT.Text = dr["TotalCost"].ToString();
dr.Close();
cn.Close();
}