如何在有效编码中将数据插入 Winform TreeView(C#)? [英] How to insert Datas to the Winform TreeView(C#) in effitive coding?

查看:25
本文介绍了如何在有效编码中将数据插入 Winform TreeView(C#)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Winform C# 和 MySQL.

I am using Winform C# and MySQL.

我有包含列名称和父 ID 的表.

I have table with columns name and parent id.

我得到了解决方案,但它太大了,每次我都想更改此代码.

I got solution,.. But its too big and each and every time I want to change this code.

请帮我添加带有父 ID 的数据.以简单格式.

Please help me to add the data's with parent id. In Simple Format.

string MyConString = ConfigurationManager.ConnectionStrings["College_Management_System.Properties.Settings.cmsConnectionString"].ConnectionString;
                MySqlConnection connection = new MySqlConnection(MyConString);
                MySqlCommand command = connection.CreateCommand();
                MySqlDataReader Reader;
                command.CommandText = "select * from menu_details";
                connection.Open();
                Reader = command.ExecuteReader();
                while (Reader.Read())
                {
                    if (Reader[2].ToString() == Convert.ToString(0))
                    {
                        treeView1.Nodes.Add(Reader[3].ToString(), Reader[1].ToString());
                    }

                    if (Reader[2].ToString() == Convert.ToString(1))
                    {
                        treeView1.Nodes[0].Nodes.Add(Reader[3].ToString(), Reader[1].ToString());
                    }

                    if (Reader[2].ToString() == Convert.ToString(2))
                    {
                        treeView1.Nodes[1].Nodes.Add(Reader[3].ToString(), Reader[1].ToString());
                    }

                    if (Reader[2].ToString() == Convert.ToString(3))
                    {
                        treeView1.Nodes[2].Nodes.Add(Reader[3].ToString(), Reader[1].ToString());
                    }

                    if (Reader[2].ToString() == Convert.ToString(4))
                    {
                        treeView1.Nodes[3].Nodes.Add(Reader[3].ToString(), Reader[1].ToString());
                    }

                    if (Reader[2].ToString() == Convert.ToString(7))
                    {
                        treeView1.Nodes[1].Nodes[0].Nodes.Add(Reader[3].ToString(), Reader[1].ToString());
                    }

                    if (Reader[2].ToString() == Convert.ToString(8))
                    {
                        treeView1.Nodes[1].Nodes[1].Nodes.Add(Reader[3].ToString(), Reader[1].ToString());
                    }

                    if (Reader[2].ToString() == Convert.ToString(9))
                    {
                        treeView1.Nodes[1].Nodes[2].Nodes.Add(Reader[3].ToString(), Reader[1].ToString());
                    }

                    if (Reader[2].ToString() == Convert.ToString(29))
                    {
                        treeView1.Nodes[1].Nodes[3].Nodes.Add(Reader[3].ToString(), Reader[1].ToString());
                    }
                }
                connection.Close();
            }
            catch { }

更新的问题 -

我尝试 Eswarn,..

I try Eswarn,..

以下格式无法正常工作@!

Below Format is not Working Properly@!

dt.Rows.Add(new string[] { "1", "One", null });
            dt.Rows.Add(new string[] { "2", "Two", null });
            dt.Rows.Add(new string[] { "3", "Three", "2" });
            dt.Rows.Add(new string[] { "4", "Four", "1" });
            dt.Rows.Add(new string[] { "5", "Five", "4" });
            dt.Rows.Add(new string[] { "6", "Six", "2" });
            dt.Rows.Add(new string[] { "7", "Seven", "1" });
            dt.Rows.Add(new string[] { "8", "Eight", "7" });
            dt.Rows.Add(new string[] { "9", "Nine", "8" });

推荐答案

创建一个新类来表示您的数据库记录:

我在 TreeNodeCollection 上使用了 Add 方法中的命名约定,其中 Key 是节点值,Text 是节点标签,因为您还没有说清楚表中的列实际上被称为什么或什么他们是类型.如果您可以将此信息添加到问题中,将会很有用.

I have used the naming convention from the Add method on the TreeNodeCollection, where Key is the node value, and Text is the node label, because you haven't made it clear what the columns in your table are actually called or what types they are. It would be useful if you could add this information to the question.

public class TreeNodeRecord
{
    public string Key { get; set; }
    public string ParentKey { get; set; }
    public string Text { get; set; }
}

通常,Key 是数据库中的主键值(通常称为 ID 之类的值).ParentKey 将是父节点的主键值(通常存储在名为 ParentId 之类的列中).您的代码似乎以这种方式将节点链接在一起,这是在数据库中存储树的最常见实现.

Typically Key would be the primary key value (usually called something like ID) from the database. ParentKey would be the primary key value of the parent node (usually stored in a column called something like ParentId). Your code appears to link the nodes together in this way, which is the most common implementation of storing a tree in a database.

例如:

  • 一个 TreeNodeRecord,其中 Key = 1 和 ParentKey = 0 是根节点
  • 一个 TreeNodeRecord,其中 Key = 2 和 ParentKey = 1 是根节点的子节点.

创建一个类来封装用数据库中的节点填充树视图的方法:

public static class TreeBuilder
{
    public static void BuildTree(TreeView treeview)
    {
        // Load database records into strongly typed list
        List<TreeNodeRecord> records = GetTreeNodeRecords();

        //Pause redrawing for the tree view control
        treeview.BeginUpdate();
        // Recursively add all items in the list to the tree
        AddNodes(records, "0", treeview.Nodes);
        // Resume redrawing for the tree view control
        treeview.EndUpdate();
    }

    // A method that reads all of the database records, and returns a strongly typed list for further processing
    private static List<TreeNodeRecord> GetTreeNodeRecords()
    {
        List<TreeNodeRecord> records = new List<TreeNodeRecord>();

        string MyConString = ConfigurationManager.ConnectionStrings["College_Management_System.Properties.Settings.cmsConnectionString"].ConnectionString;
        using (MySqlConnection connection = new MySqlConnection(MyConString))
        {
            connection.Open();

            using (MySqlCommand command = connection.CreateCommand())
            {
                MySqlDataReader reader;
                command.CommandText = "select * from menu_details";

                using (reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        TreeNodeRecord newRecord = new TreeNodeRecord
                        {
                            Key = reader[3].ToString(),
                            ParentKey = reader[2].ToString(),
                            Name = reader[1].ToString()
                        };
                        records.Add(newRecord);
                    }
                }
            }
        }

        return records;
    }

    // A recursive method to add nodes to the tree
    private static void AddNodes(List<TreeNodeRecord> records, string parentKey, TreeNodeCollection nodes)
    {
        List<TreeNodeRecord> children = records.Where(r => r.ParentKey == parentKey).ToList();

        foreach (TreeNodeRecord child in children)
        {
            TreeNode newNode = nodes.Add(child.Key, child.Text);
            AddNodes(records, child.Key, newNode.Nodes);
        }

    }
}

使用该类填充您的 TreeView 控件:

TreeBuilder.BuildTree(treeView1);

请注意正确处理您的物品很重要.如果您正在使用的对象实现了 IDisposable(具有 Dispose() 方法),则您应该在完成后调用 Dispose().上面的代码通过将对象包装在 using 语句中来实现这一点,这确保了即使引发任何异常也会调用 Dispose().

Please note it is important to dispose of your objects correctly. If an object you are using implements IDisposable (has a Dispose() method), you should call Dispose() when you are finished with it. The above code achieves this by wrapping the objects in using statements, which ensures Dispose() is called even if any exceptions are raised.

这篇关于如何在有效编码中将数据插入 Winform TreeView(C#)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆