Reflect sum of column to a label on a WinForm


Reflect sum of column to a label on a WinForm



I want to reflect the sum of a column to a label on a WinForm. I don't know what's wrong with this code:


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



The error exception that appears is: System.IndexOutOfRangeException: 'cost'


System.IndexOutOfRangeException: 'cost'




1 Answer
1



If you're going to refer to the column by name, you have to name the result of the SUM. You also don't need a loop in this case, because you know there's only one row.


SUM


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





big thanks Ken that works thanks bro
– Ezel Berkdar
2 days ago






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift