Reputation: 756
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.
Upvotes: 0
Views: 77
Reputation: 13531
Declare the variable in the outer scope:
public void rt_changed(object sender, AjaxControlToolkit.RatingEventArgs e)
{
Label l = null;
foreach (DataListItem li in datalist.Items)
{
l = li.FindControl("nl") as Label;
}
Label3.Text = (l == null ? string.Empty : l.Text);
}
Also make sure to test whether the variable is not null before using it (to avoid null pointer exception); in the example I did this using the conditional operator.
Tip 1: name your variables with a more meaningful name ('l' doesn't say much).
Tip 2: use Text
property to get label text instead of ToString()
Upvotes: 1
Reputation: 69260
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.
Upvotes: 0
Reputation: 468
Its simple,
public void rt_changed(object sender, AjaxControlToolkit.RatingEventArgs e)
{
//Label l = sender as Label;
foreach (DataListItem li in datalist.Items)
{
Label3.Text = (li.FindControl("nl") as Label).Text;
}
}
Upvotes: 0