Here i have made some code to get my categories in TreeView like --Core ---Core Subcat --Non Core ---Non Core Subcat
My code only shows me:
- Core
- Non Core
Please help me out with this code. please correct me if i'm wrong.
Thank You.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["InventoryManagerConnectionString"].ConnectionString);
private void btnLoadNodes_Click(object sender, EventArgs e)
{
DataTable dt = this.GetData("SELECT * FROM tblProductCategories WHERE Cat_ParentCat =0");
this.PopulateTree(dt, 0, null);
}
private void PopulateTree(DataTable dtParent, int parentId, TreeNode treeNode)
{
foreach (DataRow row in dtParent.Rows)
{
TreeNode child = new TreeNode
{
Text = row["Cat_Name"].ToString(),
Tag = row["Cat_ID"]
};
if (parentId == 0)
{
treeViewCat.Nodes.Add(child);
DataTable dtChild = this.GetData("SELECT * FROM tblProductCategories WHERE Cat_ParentCat="+ child.Tag);
}
else
{
treeNode.Nodes.Add(child);
}
}
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(query);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
Result Expected in TreeView:
-Core
--Core Subcat
-Non Core
--Non Core Subcat