Quantcast
Channel: Web Forms
Viewing all articles
Browse latest Browse all 23244

Variable out of scope

$
0
0

I have a little issue.

The control "div" is out of scope when trying to add child controls it in my foreach loop.  I need to re-create that control every time i = 1.  I am pretty new to c# and this is killing me.  I thought that because I declared the control outside of the foreach, it would work.  Any suggestions?

public Control MakeGalleryGrid()
    {
        images img = new images();
        List<Categories> cl = img.GetCategories();
        Control c = new Control();
        HtmlGenericControl div;
        HtmlGenericControl article;
        HtmlGenericControl header;
        HtmlGenericControl p;
        HtmlGenericControl h3;
        HyperLink hl;
        ImageButton ib;
        int i = 0;

        foreach (Categories cat in cl)
        {
            i++;

            if (i == 1)
            {
                div = new HtmlGenericControl("div");
                div.Attributes.Add("class", "row");
            }

            article = new HtmlGenericControl("article");
            article.Attributes.Add("class", "4u special");
            ib = new ImageButton();
            ib.CssClass = "image featured";
            ib.ImageUrl = cat.GalleryImage;
            ib.PostBackUrl = cat.CategoryID;
            article.Controls.Add(ib);
            header = new HtmlGenericControl("header");
            h3 = new HtmlGenericControl("h3");
            hl = new HyperLink();
            hl.Text = cat.CategoryName;
            hl.NavigateUrl = cat.CategoryID;
            h3.Controls.Add(hl);
            header.Controls.Add(h3);
            article.Controls.Add(header);
            p = new HtmlGenericControl("p");
            p.InnerText = cat.GalleryDescription;
            article.Controls.Add(p);
            div.Controls.Add(article);

            if (i == 3)
            {
                c.Controls.Add(div);
                i = 0;
            }
        }

        return c;
    }


Viewing all articles
Browse latest Browse all 23244

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>