dynamically adds html and database data (using LINQ)

advertisements

I'm trying to achieve something like this: See Image Here

where the list of categories (and list of their respective objectives are extracted from a database using LINQ)

I tried following in codebehind:

DataClassesDataContext dc = new DataClassesDataContext();

var divcount = (from cnt in dc.dml_np_Categories
                select cnt).Count();

int dv = Convert.ToInt32(divcount);

for (int i = 0; i < dv; i++)
{
    DataClassesDataContext tb = new DataClassesDataContext();
    var ctitle = (from cat in tb.dml_np_Categories
                  where cat.Pk_Category_Id == (i+1)
                  select cat.Category_Title);

    HtmlGenericControl adddiv = new HtmlGenericControl("div");
    adddiv.Attributes.Add("class", "category");
    HtmlGenericControl addh3 = new HtmlGenericControl("h3");
    addh3.Attributes.Add("class", "h3");
    addh3.InnerText = ctitle.ToString();

    catblock.Controls.Add(adddiv);
    adddiv.Controls.Add(addh3);}

I am getting following output!

See Image here

I have 3 categories in the database table, but as you can see, instead of category title it's displaying some sql.

Also I have no clue how to proceed further to add objectives under each category as hyperlink list <li>.

Need help with the LINQ query for same as well.

I know I have asked alot, but please help me of this. I'm in learning phase. I tried for a complete day on my own but could not get the desired results.


You have some issues with your code, I'll try to point them out. Your LINQ-expression is returning a query, that you call .ToString() on which results in the image above. If you call .First on the query it will return the first item int the result. I'm guessing there will only be one result in the query.

//Move this outside of the for-loop
DataClassesDataContext tb = new DataClassesDataContext();
for (int i = 0; i < dv; i++)
    {

        var ctitle = (from cat in tb.dml_np_Categories
                      where cat.Pk_Category_Id == (i+1)
                      select cat.Category_Title).First();

        HtmlGenericControl adddiv = new HtmlGenericControl("div");
        adddiv.Attributes.Add("class", "category");
        HtmlGenericControl addh3 = new HtmlGenericControl("h3");
        addh3.Attributes.Add("class", "h3");
        addh3.InnerText = ctitle.ToString();

        catblock.Controls.Add(adddiv);
        adddiv.Controls.Add(addh3);
}