标题:ListView和TreeView使用出错!
取消只看楼主
qq1023569223
Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19
来 自:湖南科技大学
等 级:贵宾
威 望:26
帖 子:2753
专家分:13404
注 册:2010-12-22
结帖率:100%
 问题点数:0 回复次数:2 
ListView和TreeView使用出错!
程序代码:
/*最近自己学了下用TreeView和ListView,遇到了问题。论坛不能上传文件了!所以只能贴出代码,希望懂得的朋友不厌其烦,帮帮我吧!*/

//问题1:获取盘符的问题.因为盘符上有一个\,父子结点间的分隔符是\,导致TreeNode.FullPath的格式有问题,如C:\\a\b\c.txt,正确是C:\a\a\c.txt,请问这有何影响?

string[] di = Directory.GetLogicalDrives();  //获取盘符,获得的格式如 C:\
foreach (string s in di)
{
   if (s.Substring(0, 1).CompareTo("A") != 0 && s.Substring(0, 1).CompareTo("G") != 0)  //除去光驱和软盘
     {
       treeView1.Nodes.Add(s);  //加在TreeView的根结点在,也就是第一层,格式如:C:\
     }
}

//问题2:遍历文件文件夹,但是结果不对,文件夹之间的归属关系乱了!请问原因在哪?

private void FindDir(TreeNode node)  //找出一个结点代表的文件夹下的文件夹
 {
    try
     {
        string[] dir = Directory.GetDirectories(node.FullPath);

          if (dir.Length > 0)  //假如有文件夹
            {
               foreach(string s in dir)
                 {
                     TreeNode tn = new TreeNode(Path.GetFileName(s));  //添加文件夹名到子结点
                     node.Nodes.Add(tn); 
                 } 
                foreach(TreeNode tn in node.Nodes)
                 {
                        FindDir(tn);  //递归遍历子文件夹的文件夹,直到最底层
                 }
             }
        }
       catch
       {

       }
}    

//问题3:ListView获取第二列的内容失败,排除了格式不正确,报错说是实例没有设置到对象上。
int ID=int.Parse(listView1.SelectedItems[0].SubItems[0].Text);  //这句为何报错?还有FocusedItems和CheckItems什么意思? 

//问题4:PerformentCounter使用出错,说是找不到计数器类型,难道我的XP SP3不支持?
using System;
using System.Collections.Generic;
using using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Interval = 1000;
            timer1.Enabled = true;
        }

        private static float PerformanceCounterFun()
        {
            PerformanceCounter pc = new PerformanceCounter("Processor", "_Total", "% Processor Time");  //这里报错
            return pc.NextValue();     
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            textBox1.Text = PerformanceCounterFun().ToString();
        }
    }
}
                    


[ 本帖最后由 qq1023569223 于 2011-5-14 11:23 编辑 ]
搜索更多相关主题的帖子: color 
2011-05-13 19:39
qq1023569223
Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19
来 自:湖南科技大学
等 级:贵宾
威 望:26
帖 子:2753
专家分:13404
注 册:2010-12-22
得分:0 
看来只有靠自己了!

   唯实惟新 至诚致志
2011-05-15 07:46
qq1023569223
Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19
来 自:湖南科技大学
等 级:贵宾
威 望:26
帖 子:2753
专家分:13404
注 册:2010-12-22
得分:0 
程序代码:
//Form1 Code
using System;
using System.Collections.Generic;
using using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using namespace MyNewTry   //晒晒代码
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private string GetDirLen(DirectoryInfo dir)
        {
            return "Unknow";
        }

        private void FindDir(TreeNode node)
        {
            try
            {
                string[] dir = Directory.GetDirectories(node.FullPath);

                if (dir.Length > 0)
                {
                    foreach(string s in dir)
                    {
                        TreeNode tn = new TreeNode(Path.GetFileName(s),0,0);
                        node.Nodes.Add(tn);
                    } 
                }
            }
            catch
            {

            }

            if (node.Nodes.Count > 0)
            {
                    foreach (TreeNode tn in node.Nodes)
                    {
                        try
                        {
                            string[] dir = Directory.GetDirectories(tn.FullPath);

                            if (dir.Length > 0)
                            {
                                foreach (string s in dir)
                                {
                                    TreeNode a = new TreeNode(Path.GetFileName(s),0,0);
                                    tn.Nodes.Add(a);
                                }
                            }
                        }
                        catch
                        {

                        }
                    }
            }
        }

        private void listDirAndFile()  //列出所选取定结点下的文件夹和文件在listview2
        {
            listView2.Items.Clear();
            TreeNode tn = treeView1.SelectedNode;
            DirectoryInfo di = new DirectoryInfo(tn.FullPath);

            try
            {
                DirectoryInfo[] dein = di.GetDirectories();

                if (dein.Length > 0)
                {
                    foreach (DirectoryInfo s in dein)
                    {
                        ListViewItem lv = new ListViewItem(new string[] { s.Name, "Folder", s.CreationTime.ToString(), GetDirLen(s) }, 0);
                        listView2.Items.Add(lv);
                    }
                }
            }
            catch
            {

            }

            try
            {
                FileInfo[] Files = di.GetFiles();

                if (Files.Length > 0)
                {
                    foreach (FileInfo s in Files)
                    {
                        ListViewItem lv;
                        string ex = s.Extension.ToLower();

                        if ((".exe") == 0)
                        {
                            lv = new ListViewItem(new string[] { s.Name, ex, s.CreationTime.ToString(), s.Length.ToString() }, 1);
                        }
                        else if ((".dll") == 0 || (".lib") == 0 || (".ocx") == 0 || (".ini") == 0 || (".sys") == 0)
                        {
                            lv = new ListViewItem(new string[] { s.Name, ex, s.CreationTime.ToString(), s.Length.ToString() }, 2);
                        }
                        else if ((".rmvb") == 0 || (".mp3") == 0 || (".avi") == 0 || (".rm") == 0)
                        {
                            lv = new ListViewItem(new string[] { s.Name, ex, s.CreationTime.ToString(), s.Length.ToString() }, 3);
                        }
                        else if ((".txt") == 0 || (".html") == 0 || (".xml") == 0 || (".htm") == 0)
                        {
                            lv = new ListViewItem(new string[] { s.Name, ex, s.CreationTime.ToString(), s.Length.ToString() }, 4);
                        }
                        else if ((".jpg") == 0 || ("jpeg") == 0 || (".bmp") == 0 || (".gif") == 0)
                        {
                            lv = new ListViewItem(new string[] { s.Name, ex, s.CreationTime.ToString(), s.Length.ToString() }, 5);
                        }
                        else
                        {
                            lv = new ListViewItem(new string[] { s.Name, ex, s.CreationTime.ToString(), s.Length.ToString() }, 6);
                        }

                        listView2.Items.Add(lv);
                    }
                }
            }
            catch
            {

            }
        }

        private void listProcess()  //列出进程在listview1
        {
            Process[] pro = Process.GetProcesses();
            foreach (Process p in pro)
            {
                ListViewItem lv = new ListViewItem(new string[] { p.ProcessName, p.Id.ToString(), p.Threads.Count.ToString(), p.WorkingSet64.ToString() });
                listView1.Items.Add(lv);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            timer1.Interval = 5000;
            timer2.Enabled = true;
            timer2.Interval = 1000;

            listProcess();
          
            string[] di = Directory.GetLogicalDrives();
            foreach (string s in di)
            {
                if (s.Substring(0, 1).CompareTo("A") != 0 && s.Substring(0, 1).CompareTo("G") != 0)
                {
                    treeView1.Nodes.Add(s);
                }
            }

            treeView1.SelectedNode = treeView1.Nodes[0];
           
            foreach (TreeNode tr in treeView1.Nodes)
            {
                FindDir(tr);
            }
     
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            listView1.Items.Clear();

            listProcess();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)  //点击树
        {                  
            textBox1.Text = treeView1.SelectedNode.FullPath;
           
            if (treeView1.SelectedNode.Nodes.Count==0)
            {
                try
                {
                    string[] dname = Directory.GetDirectories(textBox1.Text);
                    if (dname.Length > 0)
                    {
                        foreach (string s in dname)
                        {
                            treeView1.SelectedNode.Nodes.Add(Path.GetFileName(s));
                        }
                    }
                }
                catch
                {

                }

                treeView1.SelectedNode.ExpandAll();

                if (treeView1.SelectedNode.Nodes.Count > 0)
                {
                    foreach (TreeNode t in treeView1.SelectedNode.Nodes)
                    {
                        try
                        {
                            string[] str = Directory.GetDirectories(t.FullPath);

                            if (str.Length > 0)
                            {
                                foreach (string s in str)
                                {
                                    TreeNode tn = new TreeNode(Path.GetFileName(s),0,0);
                                    t.Nodes.Add(tn);
                                }
                            }
                        }
                        catch
                        {

                        }
                    }
                }
            }      
           
            listDirAndFile();         
        }

        private void killproToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string s=listView1.SelectedItems[0].SubItems[0].Text;  //报错
                int ID=int.Parse(s);
                Process[] pro = Process.GetProcesses();
                foreach (Process p in pro)
                {
                    if (p.Id == ID)
                    {
                        p.Kill();
                        break;
                    }
                }
            }
            catch(Exception)
            {
                MessageBox.Show("结束进程失败", "出错", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void listView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip1.Show(MousePosition.X,MousePosition.Y);
            }
        }

        private void delToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("确定删除?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    ListViewItem lv = listView2.SelectedItems[0];
                    if (lv.ImageIndex == 0)
                    {
                        Directory.Delete(textBox1.Text + "\\" + lv.Text, true);
                    }
                    else
                    {
                        File.Delete(textBox1.Text + "\\" + lv.Text);
                    }

                    listDirAndFile();
                }

            }
            catch (Exception o)
            {
                MessageBox.Show(o.Message, "出错", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void listView2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip2.Show(MousePosition.X, MousePosition.Y);
            }
        }

        private void atrToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ListViewItem lv = listView2.SelectedItems[0];
                if (lv.ImageIndex == 0)
                {
                    string s = textBox1.Text + "\\" + lv.Text;
                    DirectoryInfo d = new DirectoryInfo(s);

                    Form2 frm = new Form2("文件夹", s, "Unknow", d.CreationTime.ToString(), d.LastWriteTime.ToString());
                    frm.Text = d.Name + " 属性";
                    frm.ShowDialog();
                }
                else
                {
                    string s = textBox1.Text + "\\" + lv.Text;
                    FileInfo f = new FileInfo(s);

                    Form2 frm = new Form2(f.Extension.ToLower() + "文件", s, f.Length.ToString() + " Bytes", f.CreationTime.ToString(), f.LastWriteTime.ToString());
                    frm.Text = f.Name + " 属性";
                    frm.ShowDialog();
                }
            }
            catch
            {

            }
        }

        private void newFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DirectoryInfo d = new DirectoryInfo(textBox1.Text);
            string str = DateTime.Now.Millisecond.ToString();
            d.CreateSubdirectory(str);

            listDirAndFile();
        }

        private void newTxtToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string str = DateTime.Now.Millisecond.ToString();
            StreamWriter sw = new StreamWriter(textBox1.Text + "\\" + str + ".txt");
            sw.Close();

            listDirAndFile();
        }

        private float pcFun(string s1, string s2, string s3)
        {
            PerformanceCounter pc = new PerformanceCounter(s1, s2, s3);
            return pc.NextValue();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            int cpu = Convert.ToInt32((pcFun("Processor", "% Processor Time", "_Total") * 100));
            progressBar1.Value = cpu;
            label1.Text = cpu.ToString() + "%";

            int pg = Convert.ToInt32((pcFun("Process", "Page File Bytes Peak", "_Total") /1024/1024));
            progressBar2.Value = Convert.ToInt32(pg/2048.0*100);
            label2.Text = pg.ToString() + " MB";

            int idle = Convert.ToInt32(pcFun("Process", "Handle Count", "_Total"));
            label6.Text = idle.ToString();

            int trc= Convert.ToInt32(pcFun("Process", "Thread Count", "_Total"));
            label7.Text = trc.ToString();

            label8.Text = listView1.Items.Count.ToString();

            int ame=Convert.ToInt32((pcFun("Memory","System Code Total Bytes",""))/1024);
            label12.Text = ame.ToString();

            int avme=Convert.ToInt32(pcFun("Memory","Available MBytes",""));
            label13.Text = avme.ToString();

            int syscah = Convert.ToInt32(pcFun("Memory", "System Cache Resident Bytes", "") / 1024 / 1024);
            label14.Text = syscah.ToString();
        }

        private void listView2_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                ListViewItem lv = listView2.SelectedItems[0];

                if (lv.ImageIndex == 0)
                {

                    foreach (TreeNode tn in treeView1.SelectedNode.Nodes)
                    {
                        if (tn.(lv.Text) == 0)
                        {
                            treeView1.SelectedNode = tn;
                            break;
                        }
                    }         
                }
                else
                {
                    Process p = new Process();
                    p.StartInfo.FileName = textBox1.Text + "\\" + lv.Text;
                    p.Start();
                }
            }
            catch
            {

            }
        }
    }
}

//Form2 Code
using System;
using System.Collections.Generic;
using using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace MyNewTry
{
    public partial class Form2 : Form
    {
        private string[] s=new string[5];

        public Form2(params string[] str)
        {
            InitializeComponent();
            s[0] = str[0];
            s[1] = str[1];
            s[2] = str[2];
            s[3] = str[3];
            s[4] = str[4];
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            label6.Text = s[0];
            textBox1.Text = s[1];
            label7.Text = s[2];
            label8.Text = s[3];
            label9.Text = s[4];
        }
    }
}



[ 本帖最后由 qq1023569223 于 2011-5-15 10:02 编辑 ]

   唯实惟新 至诚致志
2011-05-15 10:01



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-339757-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.120260 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved