.net 连接access,在treeview中显示表中内容

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;


namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
            string connection = "Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=E:\rate\fund.accdb";//access2007;
            string sqlConnection = "SELECT * FROM account";

            OleDbConnection oleDbConnection = new OleDbConnection(connection);

            DataSet ds = new DataSet();

            OleDbDataAdapter oleDataAdapter = new OleDbDataAdapter(sqlConnection, oleDbConnection);
           
            oleDbConnection.Open();
            oleDataAdapter.Fill(ds, "account");
            dataGridView1.DataSource = ds.Tables["account"];//在dataGridView中显示account表中的内容

            //往TreeView中添加树节点
            //添加根节点
           
            TreeNode tn = new TreeNode();
            tn.Text = "科目";
            tn.Name = "0";//Name作为ID
            tn.Tag = "0";//Tag作为RootID
            tn.ImageIndex = 0;
            tn.SelectedImageIndex = 0;
            tv.Nodes.Add(tn);//该TreeView命名为tv
            tv.SelectedNode = tv.TopNode;
            //把其他节点加上去
            if (ds != null)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    tn = new TreeNode();
                    tn.Text = dr["AccName"].ToString();
                    tn.Name = dr["AccID"].ToString();//Name作为CateID
                    tn.Tag = dr["RootID"].ToString();//Tag作为RootID
                    tn.ImageIndex = 1;
                    tn.SelectedImageIndex = 1;
                    //判断是否为主节点
                    if (dr["AccID"].ToString() == dr["RootID"].ToString())
                    {
                        //主节点
                        tv.SelectedNode = tv.TopNode;
                    }
                    else
                    {
                        //其他节点
                        if (tv.SelectedNode.Name != dr["ParentID"].ToString())
                        {
                            TreeNode[] tn_temp = tv.Nodes.Find(dr["ParentID"].ToString(), true);
                            if (tn_temp.Length > 0)
                            {
                                tv.SelectedNode = tn_temp[0];
                            }
                        }
                    }
                    tv.SelectedNode.Nodes.Add(tn);
                }
                tv.ExpandAll();//展开TreeView
                tv.SelectedNode = tv.TopNode;
            }


        }
    }
}

posted @ 2008-08-10 17:44  杭东胜  阅读(557)  评论(0编辑  收藏  举报