How to hide Root node in TreeView? - c#

I am building nodes dynamically from a DB table. When I run the code the node root node also appears which wont go away. I have tried everything. Looked up on the internet but haven't find a specific solution for this problem.
My ProductCategory table looks like this
Here's the code in .cs file
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetTreeViewItems();
}
}
private void GetTreeViewItems()
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlDataAdapter da = new SqlDataAdapter("select * from ProductCategories where ParentId in (0,1,2)", con);
DataSet ds = new DataSet();
da.Fill(ds);
ds.Relations.Add("ChildRows", ds.Tables[0].Columns["ProductCategoryId"],
ds.Tables[0].Columns["ParentId"]);
foreach (DataRow level1DataRow in ds.Tables[0].Rows)
{
if (string.IsNullOrEmpty(level1DataRow["ParentId"].ToString()))
{
TreeNode parentTreeNode = new TreeNode();
parentTreeNode.Text = level1DataRow["ProductCategoryName"].ToString();
parentTreeNode.Value = level1DataRow["ProductCategoryId"].ToString();
parentTreeNode.NavigateUrl = "?catid=" + level1DataRow["ProductCategoryId"].ToString();
int i = (int)level1DataRow["ProductCategoryId"];
GetChildRows(level1DataRow, parentTreeNode);
TreeView1.Nodes.Add(parentTreeNode);
}
}
}
private void GetChildRows(DataRow dataRow, TreeNode treeNode)
{
DataRow[] childRows = dataRow.GetChildRows("ChildRows");
foreach (DataRow row in childRows)
{
TreeNode childTreeNode = new TreeNode();
childTreeNode.Text = row["ProductCategoryName"].ToString();
childTreeNode.Value = row["ProductCategoryId"].ToString();
childTreeNode.NavigateUrl = "?catid=" + row["ProductCategoryId"].ToString();
treeNode.ChildNodes.Add(childTreeNode);
if (row.GetChildRows("ChildRows").Length > 0)
{
GetChildRows(row, childTreeNode);
}
}
}
}

You can't do this. I you want a node to be invisible, but it's children to show, then the only way is not to add the root node, and add the children as root nodes.
Either that, or write your own TreeView control.

Related

C# How to obtain 2 separate class value nodes and write them to a datatable/dgv

I seem to have everything working on the name loop, but when loading the which is assigning the players name to the name column in the datagridview, but the position column appears to be looping continuously and not associating the correct value for each player.
public void button7_Click(object sender, EventArgs e)
{
DataTable dt6 = new DataTable();
dt6.Columns.Add("Name");
dt6.Columns.Add("Position");
DataRow row;
var doc = new HtmlWeb().Load("https://www.numberfire.com/nba/daily-fantasy/daily-basketball-projections");
foreach (HtmlNode node1 in doc.DocumentNode.SelectNodes(".//span[#class='player-info']//a[2]"))
{
foreach (HtmlNode node2 in doc.DocumentNode.SelectNodes(".//span[#class='player-info--position']"))
{
row = dt6.NewRow();
row["Name"] = node1.InnerHtml.Trim();
row["Position"] = node2.InnerHtml.Trim();
dt6.Rows.Add(row);
}
}
dataGridView4.DataSource = dt6;
}
Figured it out:
public void button7_Click(object sender, EventArgs e)
{
DataTable dt6 = new DataTable();
dt6.Columns.Add("Name");
dt6.Columns.Add("Position");
DataRow row;
var doc = new HtmlWeb().Load("https://www.numberfire.com/nba/daily-fantasy/daily-basketball-projections");
foreach (HtmlNode node1 in doc.DocumentNode.SelectNodes("//span[#class='player-info']"))
{
row = dt6.NewRow();
foreach (HtmlNode node in node1.SelectNodes(".//a"))
{
row["Name"] = node.InnerHtml.Trim();
}
foreach (HtmlNode node2 in node1.SelectNodes(".//span[#class='player-info--position']"))
{
row["Position"] = node2.InnerText.Trim();
}
dt6.Rows.Add(row);
}
dataGridView4.DataSource = dt6;
}

how to add new node to database with treelist?

I have a devexpress treelist with some nodes and roots. I am trying to add new nodes or roots to my treelist and of course to add it to my database. When I click a root, I would like to add a node to that root. Can somebody help me? Any ideas?
My code:
private void simpleButton2_Click(object sender, EventArgs e)
{
DbCommand cmd = cnn.CreateCommand("SELECT * FROM YETKILENDIR_OZELLIKLER", CommandType.Text);
treeList1.DataSource = cnn.GetData(cmd);
}
private void simpleButton2_Click(object sender, EventArgs e)
{
DbCommand cmd = cnn.CreateCommand("SELECT * FROM YETKILENDIR_OZELLIKLER", CommandType.Text);
Dataset Ds= cnn.GetData(cmd);
treeList1.Nodes.Clear();
if (Ds != null) {
if (Ds.Tables(1).Rows.Count > 0) {
TreeNode tNode = new TreeNode();
foreach (DataRow dr in Ds.Tables(0).Rows) {
tNode = new TreeNode();
fl = dr("FirstLevel");
tNode.Text = fl;
treeList1.Nodes.Add(tNode);
}
treeList1.ExpandAll();
}
}

How To Add Root Node In Tree View Dynamically Using Asp.net

I Want To Bind DataTable To TreeView.I Have Written Following Code.Its Working Currently,Means It Displays All Data Of DataTable But No Root Node.
List<DocumentData> lstData = GetSPDocuments();
gvDocuments.DataSource = lstData;
gvDocuments.DataBind();
DataTable dt = ConvertToDataTable(lstData);
TreeNode node1 = new TreeNode("Root");
foreach (DataRow r in dt.Rows)
{
int nodeLvl = int.Parse(r["ID"].ToString());
string nodeParent = "Folders";
string nodeName = r["Title"].ToString();
TreeNode tNode = new TreeNode(nodeName);
ht.Add(nodeLvl.ToString() + nodeName, tNode);
if (tvDocs.Nodes.Count == 0)
tvDocs.Nodes.Add(tNode);
else
{
nodeLvl--;
tvDocs.Nodes.Add(tNode);
}
}
How to Add Static Root Node Here??? Please Help!
Try this may be it can help you.
protected void Page_Load(object sender, EventArgs e)
{
conStr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
conn = new OleDbConnection(conStr);
BindTreeViewControl();
}
private void BindTreeViewControl()
{
try
{
DataSet ds = GetDataSet("Select ProductId,ProductName,ParentId from ProductTable");
DataRow[] Rows = ds.Tables[0].Select("ParentId = 0");
for (int i = 0; i < Rows.Length; i++)
{
TreeNode root = new TreeNode(Rows[i]["ProductName"].ToString(), Rows[i]["ProductId"].ToString());
root.SelectAction = TreeNodeSelectAction.Expand;
CreateNode(root, ds.Tables[0]);
treeviwExample.Nodes.Add(root);
}
}
catch (Exception Ex) { throw Ex; }
}
public void CreateNode(TreeNode node, DataTable Dt)
{
DataRow[] Rows = Dt.Select("ParentId =" + node.Value);
if (Rows.Length == 0) { return; }
for (int i = 0; i < Rows.Length; i++)
{
TreeNode Childnode = new TreeNode(Rows[i]["ProductName"].ToString(), Rows[i]["ProductId"].ToString());
Childnode.SelectAction = TreeNodeSelectAction.Expand;
node.ChildNodes.Add(Childnode);
CreateNode(Childnode, Dt);
}
}
private DataSet GetDataSet(string Query)
{
DataSet Ds = new DataSet();
try
{
OleDbDataAdapter da = new OleDbDataAdapter(Query, conn);
da.Fill(Ds);
}
catch (Exception dex) { }
return Ds;
}
and database structure for this is
// Suppress repainting the TreeView until all the objects have been created.
treeView1.BeginUpdate();
// Clear the TreeView each time the method is called.
treeView1.Nodes.Clear();
// create root node
TreeNode root = new TreeNode("Root");
// loop and add all child nodes to root node
foreach (DataRow r in dt.Rows)
{
// create child node
// add to root node
root.Nodes.Add(child);
}
// add root node to tree view
treeView1.Nodes.Add(root);
// Begin repainting the TreeView.
treeView1.EndUpdate();
Did you ever get this answered? You were almost there.
What is the name of your TreeView control? Since you never said, I am using treeView1, and modified your code to include that below:
private TreeView treeView1;
private void TreeView_DataBind() {
treeView1.Nodes.Clear();
List<DocumentData> lstData = GetSPDocuments();
gvDocuments.DataSource = lstData;
gvDocuments.DataBind();
DataTable dt = ConvertToDataTable(lstData);
TreeNode node1 = new TreeNode("Root");
treeView1.Nodes.Add(node1); // this is the step you missed
foreach (DataRow r in dt.Rows)
{
int nodeLvl = int.Parse(r["ID"].ToString());
string nodeParent = "Folders";
string nodeName = r["Title"].ToString();
TreeNode tNode = new TreeNode(nodeName);
ht.Add(nodeLvl.ToString() + nodeName, tNode);
if (tvDocs.Nodes.Count == 0)
tvDocs.Nodes.Add(tNode);
else
{
nodeLvl--;
tvDocs.Nodes.Add(tNode);
}
}
node1.Expand();
}
Easy peasy!

Add new child in TreeView from TextBox in database?

I have use the code below. And this tables in my database. I have textbox and button and i want on button click to be possible to add new child on Proba1,Proba2...What change i need to make and write in my code:
Output display:
protected void Page_Load(object sender, EventArgs e)
{
fill_Tree2();
}
void fill_Tree2()
{
DataSet PrSet = PDataset("Select * from ParentTable");
TreeView1.Nodes.Clear();
foreach (DataRow dr in PrSet.Tables[0].Rows)
{
TreeNode tnParent = new TreeNode();
tnParent.Text = dr["ParentName"].ToString();
tnParent.Value = dr["ParentID"].ToString();
tnParent.PopulateOnDemand = true;
tnParent.ToolTip = "Click to get Child";
tnParent.SelectAction = TreeNodeSelectAction.SelectExpand;
tnParent.Expand();
tnParent.Selected = true;
TreeView1.Nodes.Add(tnParent);
FillChild(tnParent, tnParent.Value);
}
}
public void FillChild(TreeNode parent, string ParentId)
{
DataSet ds = PDataset("Select * from ChildTable where ParentId =" + ParentId);
parent.ChildNodes.Clear();
foreach (DataRow dr in ds.Tables[0].Rows)
{
TreeNode child = new TreeNode();
child.Text = dr["ChildName"].ToString().Trim();
child.Value = dr["ChildId"].ToString().Trim();
if (child.ChildNodes.Count == 0)
{
child.PopulateOnDemand = true;
}
child.ToolTip = "Click to get Child";
child.SelectAction = TreeNodeSelectAction.SelectExpand;
child.CollapseAll();
parent.ChildNodes.Add(child);
}
}
protected DataSet PDataset(string Select_Statement)
{
SqlConnection SqlCon = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=cms;Integrated Security=True");
SqlDataAdapter ad = new SqlDataAdapter(Select_Statement, SqlCon);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds;
}

Populate TreeView from DataBase

I have a database table (named Topics) which includes these fields :
topicId
name
parentId
and by using them I wanna populate a TreeView in c#. How can I do that ?
Thanks in advance...
It will probably be something like this. Give some more detail as to what exactly you want to do if you need more.
//In Page load
foreach (DataRow row in topics.Rows)
{
TreeNode node = new TreeNode(dr["name"], dr["topicId"])
node.PopulateOnDemand = true;
TreeView1.Nodes.Add(node);
}
///
protected void PopulateNode(Object sender, TreeNodeEventArgs e)
{
string topicId = e.Node.Value;
//select from topic where parentId = topicId.
foreach (DataRow row in topics.Rows)
{
TreeNode node = new TreeNode(dr["name"], dr["topicId"])
node.PopulateOnDemand = true;
e.Node.ChildNodes.Add(node);
}
}
Not quite.
Trees are usually handled best by not loading everything you can at once. So you need to get the root node (or topic) which has no parentIDs. Then add them to the trees root node and then for each node you add you need to get its children.
foreach (DataRow row in topicsWithOutParents.Rows)
{
TreeNode node = New TreeNode(... whatever);
DataSet childNodes = GetRowsWhereParentIDEquals(row["topicId"]);
foreach (DataRow child in childNodes.Rows)
{
Treenode childNode = new TreeNode(..Whatever);
node.Nodes.add(childNode);
}
Tree.Nodes.Add(node);
}
this code runs perfectly for me, check it out i think it will help you :)
;
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = RunQuery("Select topicid,name from Topics where Parent_ID IS NULL");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
TreeNode root = new TreeNode(ds.Tables[0].Rows[i][1].ToString(),ds.Tables[0].Rows[i][0].ToString());
root.SelectAction = TreeNodeSelectAction.Expand;
CreateNode(root);
TreeView1.Nodes.Add(root);
}
}
void CreateNode(TreeNode node)
{
DataSet ds = RunQuery("Select topicid, name from Category where Parent_ID =" + node.Value);
if (ds.Tables[0].Rows.Count == 0)
{
return;
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
TreeNode tnode = new TreeNode(ds.Tables[0].Rows[i][1].ToString(), ds.Tables[0].Rows[i][0].ToString());
tnode.SelectAction = TreeNodeSelectAction.Expand;
node.ChildNodes.Add(tnode);
CreateNode(tnode);
}
}
DataSet RunQuery(String Query)
{
DataSet ds = new DataSet();
String connStr = "???";//write your connection string here;
using (SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand objCommand = new SqlCommand(Query, conn);
SqlDataAdapter da = new SqlDataAdapter(objCommand);
da.Fill(ds);
da.Dispose();
}
return ds;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
PopulateRootLevel();
}
private void PopulateRootLevel()
{
SqlConnection objConn = new SqlConnection(connStr);
SqlCommand objCommand = new SqlCommand(#"select FoodCategoryID,FoodCategoryName,(select count(*) FROM FoodCategories WHERE ParentID=c.FoodCategoryID) childnodecount FROM FoodCategories c where ParentID IS NULL", objConn);
SqlDataAdapter da = new SqlDataAdapter(objCommand);
DataTable dt = new DataTable();
da.Fill(dt);
PopulateNodes(dt, TreeView2.Nodes);
}
private void PopulateSubLevel(int parentid, TreeNode parentNode)
{
SqlConnection objConn = new SqlConnection(connStr);
SqlCommand objCommand = new SqlCommand(#"select FoodCategoryID,FoodCategoryName,(select count(*) FROM FoodCategories WHERE ParentID=sc.FoodCategoryID) childnodecount FROM FoodCategories sc where ParentID=#parentID", objConn);
objCommand.Parameters.Add("#parentID", SqlDbType.Int).Value = parentid;
SqlDataAdapter da = new SqlDataAdapter(objCommand);
DataTable dt = new DataTable();
da.Fill(dt);
PopulateNodes(dt, parentNode.ChildNodes);
}
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);
}
private void PopulateNodes(DataTable dt, TreeNodeCollection nodes)
{
foreach (DataRow dr in dt.Rows)
{
TreeNode tn = new TreeNode();
tn.Text = dr["FoodCategoryName"].ToString();
tn.Value = dr["FoodCategoryID"].ToString();
nodes.Add(tn);
//If node has child nodes, then enable on-demand populating
tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0);
}
}
When there are no Large Amounts of Data then it is not good to connect database, fetch data and add to treeview node again and again for child/sub nodes. It can be done in single attempt. See following sample:
http://urenjoy.blogspot.com/2009/08/display-hierarchical-data-with-treeview.html
This code runs perfectly for me. Thought it might be useful for somebody looking to display hierarchial data in a treeview.By far, i guess this is the simplest. Please check it out and upvote if it helps you.
Reference : https://techbrij.com/display-hierarchical-data-with-treeview-in-asp-net
C# code:
//dtTree should be accessible in both page load and AddNodes()
//DocsMenu is the treeview Id
DataTable dtTree = new DataTable();
//declare your connection string
protected void Page_Load(object sender, EventArgs e)
{
//DataTable dtTree = new DataTable();
using (con)
{
con.Open();
string sQuery = "Select topicId,parentid,name from tbl_topicMaster";
SqlCommand cmd = new SqlCommand(sQuery, con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtTree);
da.Dispose();
con.Close();
}
AddNodes(-1, DocsMenu.Nodes);
}
void AddNodes(int id, TreeNodeCollection tn)
{
foreach (DataRow dr in dtTree.Select("parentid= " + id))
{
TreeNode sub = new TreeNode(dr["name"].ToString(), dr["topicId"].ToString());
tn.Add(sub);
AddNodes(Convert.ToInt32(sub.Value), sub.ChildNodes);
}
}
aspx code:
<asp:TreeView ID="DocsMenu" runat="server" ImageSet="BulletedList"
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>

Categories