在一个项目中用到了读取、生成并保存TreeView内容到数据库的应用,经过研究,并着重参考了planet-source-code上的一篇文章,将原文的VB.NET代码改造成了C#代码,与大家共同分享。
using System;
using System.Windows.Forms;
using System.Collections;
using System.Data.OleDb;
namespace CallingCenterAdmin
{
///
/// TreeViewToDB 的摘要说明。
///
public class TreeViewToDB
{
// m_alDeletedNodes is used to store node deletions in memory. A call to
// CTreeView.SaveNodeCollection() will commit the deletions, and other changes,
// to the database.
public ArrayList m_alDeletedNodes;
public OleDbConnection m_conn;
public TreeViewToDB(OleDbConnection conn)
{
// Initialize the DeletedNodes collection.
m_alDeletedNodes = new ArrayList();
m_conn = conn;
}
public bool DeleteNode(TreeNode tnStart)
{
// PURPOSE: This function will delete the designated node (tnStart) and all
// of its children. The deletions will be stored in a collection. This will
// keep the deletions in memory, which configuration will allow us to rollback
// deletions.
// Get a reference to the start node parent.
TreeNode tnParent = tnStart.Parent;
// Delete the start node's children. This is performed via
// recursion, which will walk through all children regardless of number or
// arrangement. Walking through each and every child of the start node will
// allow us to synchronize node deletions with the database. Simply calling
// the remove function will remove the node and its children, but
// will leave orphan records in the database.
if (!DeleteNodeRecursive(tnStart))
{
return false;
}
// Record the deletion of the start node.
m_alDeletedNodes.Add(tnStart);
// Remove the start node from the TreeNodeCollection.
tnStart.Nodes.Remove(tnStart);
return true;
}
public bool DeleteNodeRecursive(TreeNode tnParent)
{
// PURPOSE: This function will walk through all the child nodes for a given
// node. It will remove all the nodes from the TreeNodeCollection and will
// record all deletions in memory. Deletions will be committed to the
// database when the user calls the CTreeView.SaveNodeCollection() method.