C# - [窗体] TreeView数据库数据预加载

▶ 窗体界面

▶ 源码

using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace login_demo
{
    public partial class Form2 : Form
    {
        String conn_str = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\Desktop\C-Sharp\Month_11\day1115\login_demo\login_demo\Database1.mdf;Integrated Security=True";

        public Form2()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 窗口加载时从数据库读取数据并填充
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form2_Load(object sender, EventArgs e)
        {
            addParent();
        }

        /// <summary>
        /// 迭代填充父节点
        /// </summary>
        void addParent()
        {
            String sql = "SELECT * FROM organization WHERE org_parent_id=-1";
            SqlConnection conn = new SqlConnection(conn_str);
            SqlDataReader sql_reader = null;

            //连接数据库
            try
            {
                conn.Open();
                SqlCommand command = new SqlCommand(sql, conn);
                sql_reader = command.ExecuteReader();
                while (sql_reader.Read())
                {
                    //获取节点的org_id与org_name
                    var name = sql_reader["org_name"].ToString();
                    var id = Convert.ToInt32(sql_reader["org_id"]);
                    var node = new TreeNode(name);

                    //TreeView填充
                    treeView1.Nodes.Add(node);

                    //迭代填充子节点
                    AddChildren(node, id);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Warnning Info!");
            }
            finally
            {
                sql_reader.Close();
                conn.Close();
            }
        }

        /// <summary>
        /// 添加子节点
        /// </summary>
        /// <param name="node"></param>
        /// <param name="pid">pid = parent_id</param>
        void AddChildren(TreeNode pnode,int pid)
        {
            String sql = $"SELECT * FROM organization WHERE org_parent_id={pid}";
            SqlConnection conn = new SqlConnection(conn_str);
            SqlDataReader sql_reader = null;

            //连接数据库
            try
            {
                conn.Open();
                SqlCommand command = new SqlCommand(sql, conn);
                sql_reader = command.ExecuteReader();
                while (sql_reader.Read())
                {
                    //获取节点的org_id与org_name
                    var name = sql_reader["org_name"].ToString();
                    var id = Convert.ToInt32(sql_reader["org_id"]);
                    var node = new TreeNode(name);

                    //TreeView填充
                    pnode.Nodes.Add(node);

                    //迭代填充子节点
                    AddChildren(node, id);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Warnning Info!");
            }
            finally
            {
                sql_reader.Close();
                conn.Close();
            }
        }
    }
}


C#中,要为TreeView控件获取并显示数据库中的数据,通常需要执行以下步骤: 1. 连接数据库:首先,需要使用适合的数据库连接字符串来建立与数据库的连接。这通常涉及到使用例如SqlConnection、OleDbConnection或其他数据库特有的连接类。 2. 查询数据:建立连接后,执行SQL查询或存储过程来获取需要展示在TreeView中的数据。这可以是树形结构的表或通过父/子关系查询获得的层级数据。 3. 构建TreeView节点:根据查询结果,动态创建TreeView的节点(TreeNode)。每一个节点通常代表数据表中的一个记录。 4. 设置节点关系:如果数据具有层级结构,需要为节点设置父子关系,这样可以正确地在TreeView中显示层级关系。 5. 绑定数据TreeView:将构建好的节点集合绑定到TreeView控件上。 下面是一个简化的示例代码,展示如何从数据库获取数据并填充到TreeView控件中(注意,以下代码仅为示意,实际应用中可能需要进行错误处理、安全性检查等操作): ```csharp using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void LoadTreeViewData() { string connectionString = "YourConnectionStringHere"; // 替换为实际的连接字符串 string query = "SELECT * FROM YourTable"; // 替换为实际的查询语句 using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(query, connection); TreeNode rootNode = new TreeNode("Root Node"); try { connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { // 假设每个节点的数据由两列组成:ID 和 ParentID int nodeId = reader.GetInt32(0); // ID列的索引 int parentNodeId = reader.GetInt32(1); // ParentID列的索引 string nodeName = reader.GetString(2); // 节点名称列的索引 TreeNode node = new TreeNode(nodeName); if (parentNodeId != 0) // 如果存在父节点 { // 查找父节点并添加子节点 TreeNode parentNode = rootNode.SelectSingleNode(string.Format("Nodes[{0}]", parentNodeId)); if (parentNode != null) { parentNode.Nodes.Add(node); } } else { // 父节点ID为0表示顶级节点 rootNode.Nodes.Add(node); } } reader.Close(); // 将根节点绑定到TreeView this科幻小说TreeView.Nodes.Add(rootNode); } catch (Exception ex) { MessageBox.Show("Error loading data: " + ex.Message); } } } } ``` 在这个示例中,我们没有详细说明如何处理每个节点的子节点,因为这通常取决于数据库中的数据如何组织。实际应用中,你可能需要递归遍历查询结果来正确地构建整个树形结构。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值