Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将列的总和反映到WinForm上的标签_C#_Sql Server_Winforms - Fatal编程技术网

C# 将列的总和反映到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

我想将列的总和反映到WinForm上的标签上。我不知道这个代码有什么问题:

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();       
}