---
title: "How to access the variable globally?"  
description: "How to access the variable globally?"  
author: "Anonymous User"  
published: 2014-11-13  
updated: 2014-11-14  
canonical: https://www.mindstick.com/forum/12578/how-to-access-the-variable-globally  
category: "asp.net"  
tags: ["c#", "variable"]  
reading_time: 2 minutes  

---

# How to access the variable globally?

I have a few [code](https://yourviews.mindstick.com/view/85458/alan-turing-the-mastermind-behind-cracking-the-enigma-code-during-world-war-ii) 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](https://www.mindstick.com/articles/1807/objective-c-data-types-variables-object-creation) l is null. I know it's happening because the declaration of l has been made inside the [scope](https://www.mindstick.com/interview/372/what-are-the-different-scopes-for-java-variables) of the [foreach](https://www.mindstick.com/forum/33870/how-parallel-foreach-works-internally). I don't know how to call the variable with a [value](https://www.mindstick.com/articles/23219/an-optimized-description-adds-value-to-experience-and-in-turn-effectively-guest-posting-packages) in globally.

## Replies

### Reply by Anonymous User

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.


---

Original Source: https://www.mindstick.com/forum/12578/how-to-access-the-variable-globally

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
