Sunday, September 6, 2009

Creating asp.net treeview dynamicaly with sql database for discussion thread.

If you require to display discussion thread where each main topic commented by someone and each comment again reponded by someone and this cycels goes on. Then here is the solution where I have developed same fuctionality using recursive technique. I have used asp.net treeview control where each node is binded with database.

private void CreateParentNode(TreeView p_treeview)
{
try
{
CommentDetails cdetails = new CommentDetails();
DataTable dtComments = cdetails.GetCommentWithoutResponse(suggestionId);//retriving parent node data from database
for (int i = 0; i < dtComments.Rows.Count; i++)
{
DataRow drComments = dtComments.Rows[i];
int commentId = Convert.ToInt32(drComments["commentId"].ToString());
TreeNode root = new TreeNode();
string text = drComments["PostedOn"].ToString() + " " + drComments["StaffName"].ToString();
root.Text = text;
// root.Target = "_blank";
root.NavigateUrl = "~\\Forms\\ViewComment.aspx?SuggestionId=" + suggestionId + "&CommentId=" + commentId ;
p_treeview.Nodes.Add(root);
CreateChildNode(root, commentId); //calling method for creating child node
// p_treeview.CollapseAll();
}
}
catch
{}
}

private void CreateChildNode(TreeNode p_tnode, int p_commentId, int p_discussionType)
{
try
{
CommentDetails cdetails = new CommentDetails();
DataTable dtComments = cdetails.GetResponseByCommentId(suggestionId,p_commentId); //retrieving child nodes data from database
for (int i = 0; i < dtComments.Rows.Count; i++)
{
DataRow drComments = dtComments.Rows[i];
int commentId = Convert.ToInt32(drComments["commentId"].ToString());
TreeNode child = new TreeNode();
string text = drComments["PostedOn"].ToString() + " " + drComments["StaffName"].ToString();
child.Text = text;
//child.Target = "_blank";
child.NavigateUrl = "~\\Forms\\ViewComment.aspx?SuggestionId=" + suggestionId + "&CommentId=" + commentId ;
p_tnode.ChildNodes.Add(child);
// TreeView1.Nodes.Add(p_tnode);
CreateChildNode(child, commentId); //calling this method recursively
}
}
catch
{
}
}

protected void Page_Load(object sender, EventArgs e)
{
if(!IspostBack)
CreateParentNode(TreeView1);
//call this method from page load event // Treeview1 is name of cotrol placed on aspx markup
}



Happy coding…

No comments:

Post a Comment