根据数据库表生成树。

这篇博客展示了如何在C#应用程序中利用SqlConnection连接到SQL数据库,通过查询`井信息`表并按`区块`和`井队号`分组,生成树形结构。首先获取区块的数量,然后遍历每个区块,为每个区块添加TreeNode,接着查询每个区块内的井队号,作为子节点添加到对应的区块节点下,最终在treeView1控件中展示生成的树结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private void Form1_Load(object sender, EventArgs e)
        {
           SqlConnection loadtree = new SqlConnection(@"Data Source=(local);Initial Catalog=usertest;uid=sa;pwd=123");
            loadtree.Open();
             //SqlCommand num = new SqlCommand("select count(*)  from 井信息 group by 区块", loadtree);
            //SqlDataReader sdr = num.ExecuteReader();
            SqlDataAdapter da = new SqlDataAdapter("select 区块,count(*) as cc from 井信息 group by 区块", loadtree);
            DataSet ds = new DataSet();
            da.Fill(ds,"0");
            int num1,i ,j= 0;
             num1=(Int32)ds.Tables[0].Rows.Count;
         dataGridView1.DataSource = ds.Tables[0];
            for (j = 0; j <ds.Tables[0].Rows.Count; j++)
            {   
                SqlDataAdapter da2 = new SqlDataAdapter("select distinct 井队号 from 井信息 where 区块='" + ds.Tables[0].Rows[j][0].ToString() + "'", loadtree);
                string c = j.ToString()+1;
                da2.Fill(ds,c);
                treeView1.Nodes.Add(new TreeNode(ds.Tables[0].Rows[j][0].ToString()));
                for (i = 0; i < (Int32)ds.Tables[0].Rows[j][1]; i++)
                {
                    treeView1.Nodes[j].Nodes.Add(ds.Tables[c].Rows[i][0].ToString());
                }

               
            }
链接数据库,并按照两列对应的数据生成树。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值