I ran in a strange problem using C# foreach loop and I don't get why. Can somebody explains me what is wrong with this code ?
var previouslyLoadedControls = ComposantPanel.Controls.OfType<GridView>().Where(x => x.Rows.Count > 0);
foreach (var gridView in previouslyLoadedControls)
{
gridView.DataSource = null;
gridView.DataBind();
}
var gridViewId = "GridViewOne";
var gridView = (GridView)ComposantPanel.FindControl(gridViewId);
gridView.DataSource = objects;
gridView.DataBind();
gridView.Visible = true;
Compiler tells me "A local variable named 'gridView' cannot be declared in this scope because it would give a different meaning to 'gridView', which is already used in a 'child' scope to denote something else" at line "var gridView = (GridView)ComposantPanel.FindControl(gridViewId);"
Why isn't the first gridView variable only accessible in the foreach loop scope ?
And if I just comment the second gridView declaration out then compiler tells me "The name 'gridView' does not exist in the current context" at "gridView.DataSource = objects;". So what is the scope of my foreach variable ?
i started to read some arciles (http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/ and http://csharpindepth.com/Articles/Chapter5/Closures.aspx) about closure but I still don't get it.
I use VS 2013 with .Net 4.5.1 and C# 5.