Hi ,
I have a table structure like below :
categoryID bigint , primary key , not null
categoryName nvarchar(100)
parentID bigint, not null
where as categoryID and parentID has an one-to-many relation to each other
and I want to create a nested categories with unlimited depth out of this table in my program.
I have a solution but it is not work so good and only returns the root please see the code :
private static string createlist(string catid, string parent)
{
string sql = "SELECT categoryID , categoryName FROM category WHERE parentID = " + parent;
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=sanjab;Integrated Security=True");
cn.Open();
SqlCommand cmd = new SqlCommand(sql, cn);
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
if (catid != "")
catid += ", ";
catid += sdr[1].ToString();
createlist(catid, sdr[0].ToString());
}
return catid;
}
although the code is not very efficient cause it is opening a lots of connection at the same time but with the help of above code and little bit of tweaking I can manage 2-levels depth categories but more than that means lots of trouble for me.
is there any easier method or algorithm?
regards.