C# Windows窗体应用程序,该应用程序从数据库表加载树,并将其显示在TreeView对象中?
这是我到目前为止的代码,我对循环有问题,我不明白C# Windows窗体应用程序,该应用程序从数据库表加载树,并将其显示在TreeView对象中?,c#,.net,winforms,treeview,oledbconnection,C#,.net,Winforms,Treeview,Oledbconnection,这是我到目前为止的代码,我对循环有问题,我不明白 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Windo
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication11_TreeView
{
public partial class Form1 : Form
{
OleDbConnection dbConn;
public Form1()
{
InitializeComponent();
string connStr = @"Provider=Microsoft.ACE.OLEDB.12.0; DataSource=PartsTree.accdb";
try
{
dbConn = new OleDbConnection(connStr);
dbConn.Open();
AddChildNodes(treeView1.Nodes, 0);
dbConn.Close();
dbConn.Dispose();
}
catch (OleDbException e)
{
MessageBox.Show(e.Message, "Exception!", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
}
private void AddChildNodes(TreeNodeCollection nodes, int parent)
{
string queryStr = "SELECT ID, parent_ID, description";
queryStr += "FROM parts Where parent_ID";
queryStr += (0 == parent ? "IS NULL;" : "=?");
OleDbCommand dbCmd = dbConn.CreateCommand();
dbCmd.CommandText = queryStr;
if (0 != parent)
{
OleDbParameter parameter = dbCmd.Parameters.Add("@InputParm", OleDbType.Integer);
parameter.Value = parent;
}
using (OleDbDataReader rdr = dbCmd.ExecuteReader())
{
while (rdr.Read())
{
}
rdr.Close();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
这是一个递归方法的示例:
//Link this to the AfterCheck property
private void treeViewCheckedChange(Object sender, TreeViewEventArgs e)
{
TreeNode node = (TreeNode)e.Node;
checkedNodes(node);
}
//Recursive method checks child, and then calls itself
private void checkedNodes(TreeNode parent)
{
foreach (TreeNode child in parent.Nodes)
{
child.Checked = parent.Checked;
checkedNodes(child);
}
}
@Subhash:如果您愿意,您可以自己更正格式。使用标签下的“编辑”链接。由于您还没有太多的代表点,您的编辑必须首先得到社区的批准,然后才能生效。但是你建议的每一次改进都会得到+2分。你没有告诉我们循环的问题是什么。你到底想干什么?什么不起作用?您会收到什么错误消息?首先,我想选择并添加父节点为null的节点。然后在添加每个节点时,调用一个函数并添加其子节点。冲洗并重复。这种技术需要很多查询(因此我认为它的效率不是很高),但它可能会工作。我希望使用一种称为“递归”的技术,其中函数会调用自身。有什么帮助吗?