c# winform treeview 绑定数据库显示树节点
就是一个绑定数据库的方法,我有一个父节点,下面有两个子节点。我看了好多资料但是都没有成功写出来,
这里先感谢大家了,你们用递归也好,循环也好,
我要具体点的代码,感谢
------解决方案--------------------
treeView1.ShowLines = true;
treeView1.ImageList = imageList1;//server=.;integrated security=sspi;database=db_02
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=123;database=db_02");
con.Open();
SqlCommand com = new SqlCommand("select * from tb_07", con);
SqlDataReader dr = com.ExecuteReader();
TreeNode newNode1 = treeView1.Nodes.Add("A","商品信息",1,2);//一级节点
while (dr.Read())
{
TreeNode newNode12 = new TreeNode("商品编号" + dr[1].ToString(),3,4);// 二级节点
// 3表示没有单击节点时显示的图标索引值,
newNode12.Nodes.Add("A","商品名称:" + dr[0].ToString(),5,6);
newNode12.Nodes.Add("A","商品数量:" + dr[3].ToString(),7,8);
newNode12.Nodes.Add("A", "商品价格:" + dr[2].ToString(),9,10);
newNode1.Nodes.Add(newNode12);
}
dr.Close();
con.Close();
treeView1.ExpandAll();
}
------解决方案--------------------
递归绑定节点
C# code
private void bindTreeView1()
{
string sql = "select * from dm_category";
DataTable dt = db.ExecuteDataTable(sql, CommandType.Text, null);
DataRow[] dr = dt.Select("parent_id is null");
for (int i = 0; i < dr.Length; i++)
{
TreeNode tn = new TreeNode();
tn.Text = dr[i]["category_name"].ToString();
tn.Tag = dr[i]["id"].ToString();
FillTree(tn, dt);
treeView1.Nodes.Add(tn);
}
}
private void FillTree(TreeNode node, DataTable dt)
{
DataRow[] drr = dt.Select("parent_id='" + node.Tag.ToString() + "'");
if (drr.Length > 0)
{
for (int i = 0; i < drr.Length; i++)
{
TreeNode tnn = new TreeNode();
tnn.Text = drr[i]["category_name"].ToString();
tnn.Tag = drr[i]["id"].ToString();
if (drr[i]["parent_id"].ToString() == node.Tag.ToString())
{
FillTree(tnn, dt);
}
node.Nodes.Add(tnn);
}
}
}