Vivek Kumar Vishwas

Vivek Kumar Vishwas

  • NA
  • 115
  • 56.3k

How to bind Tree View Node from database dynamically in asp

Nov 10 2017 2:26 AM
Hello,
 
I am creating a treeview in asp.net C# dybamically.
 
Data in tree view binding successfully , But Nodes is not creating to according to table data so that i could expend and collapse
 
 
aspx------------
 
 
<asp:TreeView ID="TreeView2" runat="server" ImageSet="XPFileExplorer" NodeIndent="15">
<HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px"
NodeSpacing="0px" VerticalPadding="2px"></NodeStyle>
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" HorizontalPadding="0px"
VerticalPadding="0px" />
</asp:TreeView>
 
 
 CS------------
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString.ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = this.GetData("SELECT * FROM TopParent");
this.PopulateTreeView(dt, 0, null);
BindRepeaterRight();
}
}
private void PopulateTreeView(DataTable dtParent, int parentId, TreeNode treeNode)
{
foreach (DataRow row in dtParent.Rows)
{
TreeNode child = new TreeNode
{
Text = row["cName"].ToString(),
Value = row["cId"].ToString()
};
if (parentId == 0)
{
TreeView2.Nodes.Add(child);
DataTable dtChild = this.GetData("SELECT * FROM TopParent WHERE Id = " + child.Value);
PopulateTreeView(dtChild, int.Parse(child.Value), child);
}
else
{
treeNode.ChildNodes.Add(child);
}
}
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
 
also find the attachement to solve this issues.
Please update soon. 

Attachment: treeview.rar

Answers (1)