日期:2014-05-18  浏览次数:20787 次

winform中treeview绑定sql数据库中的数据怎么弄?
在页面中我拖进来一个treeview现在要它跟数据库中的表绑定 跪求代码! 
表的字段 string m_orgid;//机构编码 string m_name;//机构名称 string m_UpdateName//上级机构名称

------解决方案--------------------
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();
                if (dr[i]["parent_id"].ToString() == "")
                {
                    FillTree(tn, dt);
                    tn.ImageIndex = 0;
                }
                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);
                        tnn.ImageIndex = 1;
                    }
                    node.Nodes.Add(tnn);
                }
            }
        }

------解决方案--------------------
C# code
// 查询
using (var conn = new SqlConnection(连接字符串))
using (var ada = new SqlDataAdapter())
{
    conn.Open();
    ada.SelectCommand.CommandText = "select m_orgid, m_name, m_UpdateName from 表名";
    var dtbl = new DataTable();
    ada.Fill(dtbl);
    Bind(null, dtbl, treeView.Nodes);
}

// 绑定方法
private static void Bind(string p, DataTable dtbl, TreeNodeCollection c)
{
    var drws = dtbl.Select("m_UpdateName" + (p != null ? ("=" + p) : " is null"));
    foreach (var drw in drws)
    {
        var n = new TreeNode((string)drw[1]);
        n.Tag = drw;
        c.Add(n);
        Bind((string)drw[2], dtbl, n.Nodes);
    }
}