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>
Related
I am working a project and i need to display on a form (frmCaterlogs) a list of items. I have successfully implimented a custom list using a user control & FlowLayOutPanel. However now i am stuck on how i can bind my caterlogs that sits on a sql database to my custom list: Here is my code. on the custome_list(CatList), i have 4 controls, Id, Titile, Description, Icon stored in database as binarydata in the sqldb. I am lost on how i can bind data to the custom list control that can look thought all the records in my database. Thanking you all in advace for your kind advices.
private void PopulateCatelog()// This code is triggered when frmcaterlogs loads.
{
int l;
string query = "SELECT * from ServicesCaterlogs";
SqlConnection con = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ListView Items = new ListView()
sda.Fill(dt);
l = dt.Rows.Count;
foreach(DataRow dr in dt.Rows) // This is where i am stuck
{
CatList iList = new CatList(dr["Item"].ToString());
iList.Title = dr;
}
CatList[] ListItem = new CatList[l];
//Loop though to check each item
for (int i = 0; i < ListItem.Length; i++)
{
ListItem[i] = new CatList();
ListItem[i].Title = fetch data for a list;
ListItem[i].Message = "fetch data for a lis";
ListItem[i].icon = Resources.Warning;
ListItem[i].IconBackground1 = Color.DarkGoldenrod;
if (FlowLayoutPanel.Controls.Count < 0)
{
FlowLayoutPanel.Controls.Clear();
}
else
{
FlowLayoutPanel.Controls.Add(ListItem[i]);
}
}
I got the desired result after altering the code as seen below
private void FrmCatalogs_Load(object sender, EventArgs e)
{
PopulateCatelog();
}
private void PopulateCatelog()
{
//Populate your listitem here
int l;
string query = "SELECT * from ServicesCaterlogs";
SqlConnection con = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
l = dt.Rows.Count;
foreach(DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["Item"].ToString());
ListViewItem des = new ListViewItem(dr["Item_Description"].ToString());
CatList[] ListItem = new CatList[l];
for (int i = 0; i < ListItem.Length - l +1 ; i++)
{
ListItem[i] = new CatList();
ListItem[i].Title = item.Text;
ListItem[i].Message = des.Text;
ListItem[i].icon = Resources.Warning;
ListItem[i].IconBackground1 = Color.DarkGoldenrod;
if (FlowLayoutPanel.Controls.Count < 0)
{
FlowLayoutPanel.Controls.Clear();
}
else
{
FlowLayoutPanel.Controls.Add(ListItem[i]);
}
}
}
}
I searched similar questions but none of them applyed to my situation.
So i have a listbox witch is supposed to fill with data depending on a selected item from a combobox.
The code worked fine but because of some changes made in the software i had to create a new form, copy/paste the design and the code to the new form.
I made the necessary adjustments but now, all the comboboxes fill and the listbox wont.
Can anyoe say why, the code is:
using System;
using System.Data;
using System.Windows.Forms;
using XXXXX.bin;
using System.Data.SqlClient;
using System.IO;
using System.Drawing.Imaging;
using System.Linq;
namespace XXXXX
{
public partial class vidro : Form
{
public static SqlConnection con = Globais.GetDbConection();
public vidro()
{
InitializeComponent();
}
private void vidro_Load(object sender, EventArgs e)
{
SqlDataAdapter SDA = new SqlDataAdapter("select distinct desempenho from vidros", con);
DataTable DTT = new DataTable();
SDA.Fill(DTT);
desempenho.Items.Clear();
foreach (DataRow ROW in DTT.Rows)
{
desempenho.Items.Add(ROW["desempenho"].ToString());
}
SqlDataAdapter SDA2 = new SqlDataAdapter("select distinct valu from vidros", con);
DataTable DTT2 = new DataTable();
SDA2.Fill(DTT2);
valu.Items.Clear();
foreach (DataRow ROW in DTT2.Rows)
{
valu.Items.Add(ROW["valu"].ToString());
}
SqlDataAdapter SDA3 = new SqlDataAdapter("select distinct fs from vidros", con);
DataTable DTT3 = new DataTable();
SDA3.Fill(DTT3);
fsolar.Items.Clear();
foreach (DataRow ROW in DTT3.Rows)
{
fsolar.Items.Add(ROW["fs"].ToString());
}
SqlDataAdapter SDA4 = new SqlDataAdapter("select distinct sel from vidros", con);
DataTable DTT4 = new DataTable();
SDA4.Fill(DTT4);
select.Items.Clear();
foreach (DataRow ROW in DTT4.Rows)
{
select.Items.Add(ROW["sel"].ToString());
}
SqlDataAdapter SDA5 = new SqlDataAdapter("select distinct compo from vidros", con);
DataTable DTT5 = new DataTable();
SDA5.Fill(DTT5);
select.Items.Clear();
foreach (DataRow ROW in DTT5.Rows)
{
compo.Items.Add(ROW["compo"].ToString());
}
SqlDataAdapter SDA6 = new SqlDataAdapter("select distinct sel from vidros", con);
DataTable DTT6 = new DataTable();
SDA6.Fill(DTT6);
select.Items.Clear();
foreach (DataRow ROW in DTT6.Rows)
{
select.Items.Add(ROW["sel"].ToString());
}
}
private void desempenho_SelectedIndexChanged(object sender, EventArgs e)
{
FillData();
}
private void valu_SelectedIndexChanged(object sender, EventArgs e)
{
FillData();
}
private void fsolar_SelectedIndexChanged(object sender, EventArgs e)
{
FillData();
}
private void selec_SelectedIndexChanged(object sender, EventArgs e)
{
FillData();
}
private void compo_SelectedIndexChanged(object sender, EventArgs e)
{
FillData();
}
private void FillData()
{
string combo1value = desempenho.Text;
string combo2value = valu.Text;
string combo3value = fsolar.Text;
string combo4value = select.Text;
string combo5value = compo.Text;
string query = "select [desc],[enchimento],[compo] from vidros where 1=1 ";
string queryWhere = "";
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
sda.SelectCommand = cmd;
if (combo1value != "")
{
queryWhere += " and desempenho = #emp ";
sda.SelectCommand.Parameters.Add("#emp", SqlDbType.NVarChar).Value = combo1value;
}
if (combo2value != "")
{
queryWhere += " and valu = #emp2 ";
sda.SelectCommand.Parameters.Add("#emp2", SqlDbType.NVarChar).Value = combo2value;
}
if (combo3value != "")
{
queryWhere += " and fs = #emp3 ";
sda.SelectCommand.Parameters.Add("#emp3", SqlDbType.NVarChar).Value = combo3value;
}
if (combo4value != "")
{
queryWhere += " and sel = #emp4 ";
sda.SelectCommand.Parameters.Add("#emp4", SqlDbType.NVarChar).Value = combo4value;
}
if (combo5value != "")
{
queryWhere += " and compo = #emp5 ";
sda.SelectCommand.Parameters.Add("#emp5", SqlDbType.NVarChar).Value = combo5value;
}
sda.SelectCommand.CommandText = query + queryWhere;
DataTable DTT = new DataTable();
sda.Fill(DTT);
listView1.Items.Clear();
for (int i = 0; i < DTT.Rows.Count; i++)
{
DataRow dr = DTT.Rows[i];
ListViewItem listitem = new ListViewItem(dr["desc"].ToString());
listitem.SubItems.Add(dr["enchimento"].ToString());
listitem.SubItems.Add(dr["compo"].ToString());
listView1.Items.Add(listitem);
}
}
Because you transferred the code to a new form you will need to hook up your event handlers for the controls.
This can be done in the designer by selecting a control and going to its event tab (the lightning shape near properties)
Or in code by doing: controlName.EventName += eventHandlerMethodName;
Example: button1.Click += button1_Click;
Make sure that the control names(ComboBox and Listbox) are the same as in the copied code and add eventlisteners for each control after that.
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.
I am currently developing a C# Windows Form Application.
Now I am trying to use a SQL Command to retrieve information from the database to fill in the information that I need to have in my Application.
A sample query would be "select * from Location"
In the Location table there would be variables like locationId, LocationName , districId etc etc.
I used the following code
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connectionstring");
SqlDataAdapter ada = new SqlDataAdapter("select * from MasterLocation", con);
DataTable dt = new DataTable();
ada.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
ListViewItem listitem =new ListViewItem(dr["pk_Location_ID"].ToString());
listitem.SubItems.Add(dr["var_Location_Name"].ToString());
listitem.SubItems.Add(dr["fk_int_District_ID"].ToString());
listitem.SubItems.Add(dr["fk_int_Company_ID"].ToString());
listView1.Items.Add(listitem);
}
The output is:
but it should be like this:
you have to change some code
private void button1_Click(object sender, EventArgs e)
{
listView1.View = View.Details;
SqlConnection con = new SqlConnection("connectionstring");
SqlDataAdapter ada = new SqlDataAdapter("select * from MasterLocation", con);
DataTable dt = new DataTable();
ada.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
ListViewItem listitem = new ListViewItem(dr["pk_Location_ID"].ToString());
listitem.SubItems.Add(dr["var_Location_Name"].ToString());
listitem.SubItems.Add(dr["fk_int_District_ID"].ToString());
listitem.SubItems.Add(dr["fk_int_Company_ID"].ToString());
listView1.Items.Add(listitem);
}
Added the following code
listView1.View = View.Details;
and it worked.
private void FormView_Load(object sender, EventArgs e)
{
sample = new DataTable(); //Sample Data
sample.Columns.Add("id", typeof(string));
sample.Columns.Add("name", typeof(string));
sample.Rows.Add("1", "apple");
sample.Rows.Add("2", "acer");
sample.Rows.Add("3", "alpha");
sample.Rows.Add("4", "beat");
sample.Rows.Add("5", "ball");
sample.Rows.Add("6", "cat");
sample.Rows.Add("7", "catch");
sample.Rows.Add("10", "zebra");
listViewEx1.View = View.Details;
listViewEx1.Columns.Add("id");
listViewEx1.Columns.Add("name");
}
listViewEx1.Items.Clear();
listViewEx1.FullRowSelect = true;
foreach (DataRow row in sample.Rows)
{
ListViewItem item = new ListViewItem(row["id"].ToString());
item.SubItems.Add(row["name"].ToString());
listViewEx1.Items.Add(item); //Add this row to the ListView
}
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;
}