Accessing a string variable from one method to another which is declared globally is giving null value

StackOverflow https://stackoverflow.com/questions/20486798

  •  30-08-2022
  •  | 
  •  

Question

I am working on a web app;ication based on asp.net with c#,I have two methods specified below.

public partial class ClerkReception_CreateRecords : System.Web.UI.Page
{
string patid;   
protected void ddryear_textchanged(object sender, EventArgs e)
{
    string month = "";
    if (ddrmonth.SelectedItem.Text == "Jan")
    {
        month = "01";

    }
    else if (ddrmonth.SelectedItem.Text == "Feb")
    {
        month = "02";
    }
    else if (ddrmonth.SelectedItem.Text == "Mar")
    {
        month = "03";
    }



    string year;
    year = ddryear.SelectedItem.Text;
    string locid = Session["Location"].ToString();

    patid = locid + month + year;//Ex:AT112013


    myConnection obj = new myConnection();

    //string result = obj.fnDisplayManualRecords(year, month, locid);
    string result = obj.fnDisplayManualRecords1(patid);

    txtlast.Text = result.ToString();
    if (ddrmonth.SelectedItem.Text != null || ddryear.SelectedItem.Text != null)
    {
        txtlast.Visible = true;
        lbllast.Visible = true;
        BtnProceed.Visible = true;
    }

}

This is a method used when a item is selected from dropdownlist,where the patid returns the value.

I need to access the same value of patid inside a another method shown below,Hence I declared the patid as global variable so that I can access the value in any method.But its giving null.How to retieve the vale from one method to another method?

protected void BtnProceed_Click(object sender, EventArgs e)
{


    string x = patid;//shows null
    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand("select top 1(SUBSTRING(patientid,9,4)) as MaxpatientID  from Patient_Data where PatientID like '"+patid+"%' order by PatientID desc;", cn))
        {
            try
            {

                cn.Open();

                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    //int Patcount;
                    if (rdr.Read())
                    {
                        int Patcount = int.Parse(rdr["MaxpatientID"].ToString());
                        // if(Patcount == 0)


                    }
                }
            }
            catch (Exception ex)
            {

                // handle errors here
            }

        }
    }

}
}
Was it helpful?

Solution

The global variables are created / intialized between postback in asp.net and they do not retain the values between postback as http is stateless protocol, you need to use ViewState for that. You can read more about ViewState and Stateless protocol over here.

To set value in ViewState

ViewState["patid"] =  locid + month + year;//Ex:AT112013;

To get value from ViewState

string patid = ViewState["patid"].ToString();

View State

View state's purpose in life is simple: it's there to persist state across postbacks. (For an ASP.NET Web page, its state is the property values of the controls that make up its control hierarchy.) This begs the question, "What sort of state needs to be persisted?" To answer that question, let's start by looking at what state doesn't need to be persisted across postbacks. Recall that in the instantiation stage of the page life cycle, the control hierarchy is created and those properties that are specified in the declarative syntax are assigned. Since these declarative properties are automatically reassigned on each postback when the control hierarchy is constructed, there's no need to store these property values in the view state. You can read more about viewstate here.

OTHER TIPS

Welcome to the world of post backs, each post back recreates the page (class) variables, so you need to save it before post back or it will be gone.

Use a cache object, such as Session to maintain values between post back and page navigation. Session gives you the power to store and retrieve objects across multiple pages in your application, including just one if you are continually posting back to it.

You can use Session, like this:

Storing value in Session:

Session["ValueToKeep"] = "My important information";

Retrieving value from Session:

// Make sure it is in session cache before we try to get it
if(Session["ValueToKeep"] != null)
{
    string valueINeed = Session["ValueToKeep"].ToString();
}

Note: All items stored in Session are Objects thus the usage of .ToString() on the Session item. An item is boxed as an object when inserted into Session, but must be unboxed (cast) when retrieved.

You class level variables are re-created on postback. You will need to persist them somewhere that continues across requests.. such as ViewState, Session, etc.

The best way to interact with two methods / functions / event-function in side class is just declaring its accessible modifiers to public and you can call any object of that class after initialize some value to it.

 public void ddryear_textchanged(object sender, EventArgs e) {....}
 public void BtnProceed_Click(object sender, EventArgs e) {....}

create one variable inside class like string x; and initialize it in constrictor { x="some text "; } this is how code works...

There are many ways to get the value of global parameter, one way is to define the parameter as static

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top