C# WinForm中TreeView无法从SQL表填充及多级从属表树结构实现问询
Hey there! Let's break down what's going wrong here and fix your TreeView step by step.
First: Fix the Blank TreeView (Immediate Issue)
Your TreeView is showing up blank for the simplest reason—you never actually run your Loadtree() method! Looking at your Form2_Load event, there's only commented-out fill code, no call to trigger data loading. Add this line to your Form2_Load method to fix that:
private void Form2_Load(object sender, EventArgs e) { Loadtree(); // This kicks off the tree data loading process }
Second: Fix the Table & Hierarchy Mix-Up
Right now, your code has the table relationships completely reversed:
- You're using the Superobject table adapter to load top-level nodes (filtering for
МакроКод is null), but top-level nodes should come from the Macroobject table (since Macroobjects are the highest level with no parent). - Then you're using the Macroobject table adapter to load child nodes for Superobjects, which is backwards—child Superobjects should be pulled from their own table, filtered by the parent Macroobject's ID.
Let's clarify the expected hierarchy first (adjust field names to match your actual database if needed):
- Macroobject: Top-level nodes, primary key =
МакроКод, display text =макрообъект - Superobject: Child of Macroobject, links to parent via
МакроКод, primary key =СуперКод, display text =суперобъект - Object: Child of Superobject, links to parent via
СуперКод, display text =объект
Third: Rewrite the Loading Logic for Full Hierarchy
Here's corrected code that properly loads all three levels of your tree, with clear separation of each node type:
namespace WindowsFormsApp1 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } // Load top-level Macroobject nodes private void Loadtree() { // Get all Macroobjects (top-level, no parent) DataTable macroTable = this.выборМакроОбъектTableAdapter.GetData(); foreach (DataRow dr in macroTable.Select("МакроКод is null")) { TreeNode macroNode = new TreeNode(); macroNode.Text = dr["макрообъект"].ToString(); macroNode.Tag = dr["МакроКод"]; // Store Macro ID to load children treeView1.Nodes.Add(macroNode); // Load Superobject children for this Macroobject LoadSuperNodes(macroNode); } } // Load Superobject nodes under a given Macroobject private void LoadSuperNodes(TreeNode parentMacroNode) { if (parentMacroNode.Tag == DBNull.Value) return; // Skip if no valid Macro ID DataTable superTable = this.выборСуперОбъектTableAdapter.GetData(); // Filter Superobjects where parent Macro ID matches the node's tag string filter = $"МакроКод = {parentMacroNode.Tag}"; foreach (DataRow dr in superTable.Select(filter)) { TreeNode superNode = new TreeNode(); superNode.Text = dr["суперобъект"].ToString(); superNode.Tag = dr["СуперКод"]; // Store Super ID to load children parentMacroNode.Nodes.Add(superNode); // Load Object children for this Superobject LoadObjectNodes(superNode); } } // Load Object nodes under a given Superobject private void LoadObjectNodes(TreeNode parentSuperNode) { if (parentSuperNode.Tag == DBNull.Value) return; // Skip if no valid Super ID // Replace with your actual Object table's TableAdapter DataTable objectTable = this.выборОбъектTableAdapter.GetData(); // Filter Objects where parent Super ID matches the node's tag string filter = $"СуперКод = {parentSuperNode.Tag}"; foreach (DataRow dr in objectTable.Select(filter)) { TreeNode objectNode = new TreeNode(); objectNode.Text = dr["объект"].ToString(); objectNode.Tag = dr["ОбъектКод"]; // Optional: store Object ID if needed parentSuperNode.Nodes.Add(objectNode); } } private void Form2_Load(object sender, EventArgs e) { Loadtree(); // Trigger the loading process } } }
Quick Tips for Your C# Journey
- Double-Check Field Names: Make sure all field references (like
МакроКод,СуперКод) match exactly what's in your database and DataSet—typos here are a common pain point for new developers. - Null Safety: The checks for
DBNull.Valueprevent crashes if a node's tag is empty (e.g., a top-level node with no parent ID). - Filter Improvements: For production code, avoid string concatenation for filters (it can cause errors with string IDs or special characters). Instead, use LINQ to query your DataTables, but for learning purposes, the current approach works fine.
内容的提问来源于stack exchange,提问作者Олег Литвинов
相关产品推荐
相关产品推荐

