I'm trying to return database rows - category and sub category in this format:
Category 1
SubCategory
SubCategory
SubCategory
Category 2
SubCategory
SubCategory
SubCategory
In other words return the category with the sub categories that belong to it underneath.
I am storing the category and sub category in a List, if this is the way to go, I'm guessing my problem is my for or foreach syntax
Here is the full code:
public class Categories
{
public string Name { get; set; }
public string SubName { get; set; }
}
public void Category()
{
DataTable table = new DataTable();
DataTable subTable = new DataTable();
List<Categories> category = new List<Categories>();
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = "Category_Admin_GetAll";
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
table.Load(reader);
reader.Close();
conn.Close();
}
using(SqlCommand comm = new SqlCommand())
{
comm.Connection=conn;
comm.CommandType= CommandType.StoredProcedure;
comm.CommandText = "SubCategory_Admin_GetAll";
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
subTable.Load(reader);
reader.Close();
conn.Close();
}
}
foreach (DataRow dRow in table.Rows)
{
category.Add(new Categories { Name = dRow["Name"].ToString() });
}
foreach (DataRow dRow in subTable.Rows)
{
category.Add(new Categories { SubName = dRow["SubCategoryName"].ToString() });
}
int t = category.Count;
resultSpan.InnerHtml += "<table class='table_category'>";
resultSpan.InnerHtml += "<tr><td>ACTIVE</td><td>NAME</td></tr>";
resultSpan.InnerHtml +="<tr><td></td><td>"+ category[0].Name+"</td></tr>";
for (int i = 0; i < t; i++)
{
resultSpan.InnerHtml += "<tr><td></td><td>" + category[i].SubName + "</td></tr>";
}
resultSpan.InnerHtml += "</table>";
}
CategoryId, SubCategoryId, Nameand change the Categories class toCategoryId, Name. If you start there, the rest will follow quite naturally.