如何在c# treeview控件动态绑定数据库,实现2级目录,添加父节点并在父节点下添加子节点

2024-12-27 22:30:06
推荐回答(2个)
回答1:

那就看看我做的,建立一个mutua类文件,在里面写代码

namespace *******
{
    class mutua
    {
        public static SqlConnection conn = null;
        public DataSet ds = null;
        public SqlDataAdapter sda = null;
        public String ExceptionStr = "";
        public void Openlink()
        {
            conn = new SqlConnection();
            conn.ConnectionString = "Server=192.168.1.240;uid=sa;pwd=chaimisin8712*;database=GZ_DATA";
            try
            {
                conn.Open();
            }
            catch
            {
                conn.Close();
            }
        }
        public void linkSQL(String sql)
        {
            if (conn != null)
            {
                ds = new DataSet();
                sda = new SqlDataAdapter();
                sda.SelectCommand = new SqlCommand(sql, conn);
                SqlCommandBuilder builder = new SqlCommandBuilder(sda);
                sda.Fill(ds);
            }
        }
     }
 }

启动窗体初始化时就openlink打开链接,后面应用到窗体使用treeview就写这样的代码


        void getView()
        {
            mutua s = new mutua();
            mutua d = new mutua();
            mutua e = new mutua();
            s.linkSQL("Select Distinct bm from a_gydy order by bm");
            if (s.ds != null)
            {
                for (int i = 0; i < s.ds.Tables[0].Rows.Count; i++)
                {
                    treeView1.Nodes.Add(s.ds.Tables[0].Rows[i][0].ToString());
                    d.linkSQL("Select Distinct gy from a_gydy where bm='" + s.dss.Tables[0].Rows[i][0].ToString() + "' order by gy");  
                    if (d.ds != null)
                    {
                        for (int j = 0; j < d.ds.Tables[0].Rows.Count; j++)
                        {
                            treeView1.Nodes[i].Nodes.Add(d.ds.Tables[0].Rows[j][0].ToString());
                            d.linkSQL("Select Distinct gw from c_gy where bm='" + s.ds.Tables[0].Rows[i][0].ToString() + "' and gy='" + d.ds.Tables[0].Rows[j][0].ToString() + "' and gw<>'' order by gw");
                            if (e.ds != null)
                            {
                                for (int k = 0; k < e.ds.Tables[0].Rows.Count; k++)
                                {
                                    treeView1.Nodes[i].Nodes[j].Nodes.Add(e.ds.Tables[0].Rows[k][0].ToString());
                                }
                            }
                        }
                    }
                }
            }

给treeView1加了三级目录

回答2:

那挨接