How to fetch data in a variable in asp.net C#

Viewed 110

I am trying to fetch the data in a decimal variable. I highly need your assistance to do so. if I test the query but put the fetched value in the label, it works without any problem. However, I want to get it in the decimal humidity as I want to compare this value with the threshold. Could you help me with this? Your help with being highly appreciated below is the code

the output: I still get 20 which is the declared value in the code.

namespace IoTSmartFarming
{
    public partial class DataVisualization : System.Web.UI.Page
    {
        string strcon = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            showHumidity();
        }
    
        private decimal getHumidity()
        {
            SqlConnection conn = new SqlConnection(strcon);
            if (conn.State == System.Data.ConnectionState.Closed)
            {
                conn.Open();
            }
            decimal humidity = 20;
            SqlCommand cmd = new SqlCommand("SELECT TOP 1 value from Humidity ORDER BY time desc", conn);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                Label4.Text= dr.GetValue(0).ToString();
            }

            return humidity;
        }

        private void showHumidity()
        {
            decimal actHumidity = getHumidity();
            Label4.Text = actHumidity.ToString();

            if(actHumidity>100 || actHumidity < 10)
            {
                Label5.Visible = false;
                Label6.Visible = true;
            }

        }
    }
}
1 Answers

You forgot to assign your variable. All that you need is add an variable assignment:

humidity = dr.GetDecimal(0);
Related