Click here to Skip to main content
14,493,689 members
Rate this:
Please Sign up or sign in to vote.
See more:
I have this program code here that I use throughout my forms:

void totalqty()
        {
            string constring = "Data Source=D-HOS-MIS2;Initial Catalog=Consignment_db;Persist Security Info=True;User ID=sa;Password=t.july.01";
            string query = "select sum(SRT_Qty) as SRT_Total from StockReqTemp";
            SqlConnection con_db = new SqlConnection(constring);
            SqlCommand cmd = new SqlCommand(query, con_db);
            SqlDataReader reader;

            try
            {
                con_db.Open();
                reader = cmd.ExecuteReader();
                while(reader.Read())
                {
                    
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


What I have tried:

I have tried:

SR_TotalQty.Text = (dr["SRT_Total"].ToString());


but it doesn't work. I know how to show data from database through listview and and combobox but not in a textbox.
Posted
Updated 20-Jun-18 20:22pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Since you are only working with a single aggregate value, I'd use ExecuteScalar:
string constring = "Data Source=D-HOS-MIS2;Initial Catalog=Consignment_db;Persist Security Info=True;User ID=sa;Password=t.july.01";
string query = "select sum(SRT_Qty) as SRT_Total from StockReqTemp";
using (SqlConnection con_db = new SqlConnection(constring))
    {
    using (SqlCommand cmd = new SqlCommand(query, con_db))
        {
        try
            {
            con_db.Open();
            SR_TotalQty.Text = cmd.ExecuteScalar().ToString();
            }
        catch (Exception ex)
            {
            MessageBox.Show(ex.Message);
            }
        }
    }
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100