Home > DeveloperSection > Forums > How to access the variable globally?
Goti Bandu

Total Post:119

Points:835
Posted on    November-13-2014 10:44 PM

 ASP.Net C#  Variable 
Ratings:


 1 Reply(s)
 574  View(s)
Rate this:

I have a few code lines like this,

public void rt_changed(object sender, AjaxControlToolkit.RatingEventArgs e)

{

    //Label l = sender as Label;

    foreach (DataListItem li in datalist.Items)

    {

 

      Label l = li.FindControl("nl") as Label;

 

    }

    Label3.Text = l.ToString(); // l values is not getting

 }

Here the variable l is null. I know it's happening because the declaration of l has been made inside the scope of the foreach. I don't know how to call the variable with value in globally.



Jeet Verma
Jeet Verma

Total Post:110

Points:776
Posted on    November-14-2014 2:00 AM

You just need to move the declaration of the l variable outside of the loop to make it available. You can declare (tell what it is) in a different place than where you assign it a value.

public void rt_changed(object sender, AjaxControlToolkit.RatingEventArgs e)

{

  // Declare l, also give it a default value, in the case that datalist is empty.

  Label l = null;

  foreach (DataListItem li in datalist.Items)

  {

    l = li.FindControl("nl") as Label;

  }

  Label3.Text = l.ToString(); // l values is not getting

}

Please note that l will only get assigned to the last value in the datalist collection, which probably isn't exactly what you want.


Don't want to miss updates? Please click the below button!

Follow MindStick