简体   繁体   English

如何在一个用户控件中显示多个进程?

[英]How to display multiple processes in one user control?

A conditional example. 一个有条件的例子。
There are: 有:
- data files (used for example (file "Data")): -数据文件(例如(文件“数据”)使用):
.. \\ 01 \\ data \\ fol_data_1 \\ fol_data_1.txt .. \\ 01 \\数据\\ fol_data_1 \\ fol_data_1.txt
.. \\ 01 \\ data \\ fol_data_2 \\ fol_data_2.txt .. \\ 01 \\数据\\ fol_data_2 \\ fol_data_2.txt
.. \\ 01 \\ data \\ fol_data_3 \\ fol_data_3.txt .. \\ 01 \\数据\\ fol_data_3 \\ fol_data_3.txt
The "Data" files are displayed in the tree view. “数据”文件显示在树形视图中。
The user can add, delete, modify the "Data" files. 用户可以添加,删除,修改“数据”文件。
Scenario. 场景。
1. The user. 1.用户。 Selects one or more "Data" files (fol_data_ "N") in the tree; 在树中选择一个或多个“数据”文件(fol_data_“ N”); The choice is made by means of translating CheckBoxes to "true"; 通过将CheckBoxes转换为“ true”来进行选择。
2. The user. 2.用户。 Click "Run" button (button3); 单击“运行”按钮(button3);
3. The program. 3.程序。 Creates tables "DateTable" for each file "Data"; 为每个文件“数据”创建表“ DateTable”;
4. The program. 4.程序。 Creates "DateGrid" for each "Data" file; 为每个“数据”文件创建“ DateGrid”;
5. The program. 5.程序。 Parse data from the "Data" file; 解析“数据”文件中的数据;
6. The program. 6.程序。 He writes in "DateTable"; 他在“ DateTable”中写道;
7. The program. 7.程序。 Brings in "DataGrid"; 带入“ DataGrid”;
Items 3 - 7 must be executed simultaneously for all selected "Data" files. 必须同时为所有选定的“数据”文件执行项目3-7。
Items 3 - 7 are placed in the user control "GridUserControl". 项目3-7放置在用户控件“ GridUserControl”中。
While the program performs the process of transferring lines from the "Data" file to "DateTable", the user can navigate the tree with the cursor. 在程序执行将行从“数据”文件传输到“日期表”的过程时,用户可以使用光标浏览树。
If the user enters the "Data" file for a process for which it is already running, then "panel3" displays "GridUserControl" with the current "DateGrid" filling state in rows/ 如果用户为已经为其运行的进程输入“数据”文件,则“ panel3”显示“ GridUserControl”以及当前“ DateGrid”填充状态(以行/

Question. 题。
1. How to implement this scenario? 1.如何实现这种情况?
2. What are the comments (proposals) for implementing this scenario? 2.对实施此方案有何评论(建议)?

PROJEKT - LINK PROJEKT- 链接
pic_1 PIC_1

GridUserControl.cs GridUserControl.cs

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

namespace TreeView_FolderTree
{
    public partial class GridUserControl : UserControl
    {

        public string pathFileData;

        public GridUserControl(string pathFileData)
        {
            InitializeComponent();

            // Обрабатываем данные
            //Или записываем их в поле
            this.pathFileData = pathFileData;

        }

        private void GridUserControl_Load(object sender, EventArgs e)
        {
            start_GridUserControl();
        }

        public void start_GridUserControl()
        {
            DataTable table_1;

            //привязка данных
            BindingSource bs;


            table_1 = new DataTable();
            table_1.Columns.Add("Content", typeof(string));
            table_1.Columns.Add("DateTime", typeof(DateTime));

            bs = new BindingSource(table_1, "");

            dataGridView1.DataSource = bs;
            dataGridView1.Columns["DateTime"].DefaultCellStyle.Format = "dd.MM.yyyy HH:mm:ss tt";



            // Читаем файл "Данные"
            string[] lines = System.IO.File.ReadAllLines(pathFileData);

            // System.Console.WriteLine("Contents of WriteLines2.txt = ");
            foreach (string line in lines)
            {
                //создаем новую запись
                DataRow newrow = table_1.NewRow();

                //заполняем ее данными
                newrow["Content"] = line;
                newrow["DateTime"] = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss");

                //заносим запись в таблицу
                table_1.Rows.Add(newrow);

                //обновляем данные в гриде
                bs.ResetBindings(false);

                // Пауза
                System.Threading.Thread.Sleep(1500);
                Application.DoEvents();

            }
        }


    }
}

Did so. 是的

Am I on the right track or are there better ways? 我是在正确的道路上还是有更好的方法?

* Code Form1.cs * *代码Form1.cs *
Creating TreeView 创建TreeView

#region  *** TreeView Создание***
        private void InitFolders()
        {
            //Отключаем любую перерисовку
            //иерархического представления.
            treeView1.BeginUpdate();

            //Инициализируем новую переменную предоставляющую методы экземпляра
            //класса для создания, перемещения и перечисления
            //в каталогах и подкаталогах.
            System.IO.DirectoryInfo di;
            try
            {
                //Вызываем метод GetDirectories с передачей в качестве параметра, пути к 
                //выбранной директории. Данный метод возвращает
                //массив имен подкаталогов.
                string[] root = System.IO.Directory.GetDirectories(path);

                //Проходимся по всем полученным подкаталогам.
                foreach (string s in root)
                {
                    try
                    {
                        //Заносим в переменную информацию
                        //о текущей директории.
                        di = new System.IO.DirectoryInfo(s);
                        //Вызов метода сканирования с
                        //передачей в качестве параметра, информации
                        //о текущей директории и объект 
                        //System.Windows.Forms.TreeNodeCollection,
                        //который предоставляет узлы
                        //дерева, назначенные элементу управления 
                        //иерархического представления.
                        BuildTree(di, treeView1.Nodes);
                    }
                    catch { }
                }
            }
            catch { }
            //Разрешаем перерисовку иерархического представления.
            treeView1.EndUpdate();
        }       

        //Процесс получения папок и файлов
        private void BuildTree(System.IO.DirectoryInfo directoryInfo, TreeNodeCollection addInMe)
        {
            //Добавляем новый узел в коллекцию Nodes
            //с именем текущей директории и указанием ключа 
            //со значением "Folder".
            TreeNode curNode = addInMe.Add("Folder", directoryInfo.Name);

            //addInMe.Add(directoryInfo.FullName, directoryInfo.Name, 
            //тут можно указать номер картинки для узла из imageCollection);

            //Перебираем папки.
            foreach (System.IO.DirectoryInfo subdir in directoryInfo.GetDirectories())
            {
                //Запускам процесс получения папок и файлов 
                //с текущей найденной директории.
                BuildTree(subdir, curNode.Nodes);
            }

            //Перебираем файлы
            foreach (System.IO.FileInfo file in directoryInfo.GetFiles())
            {
                //Добавляем новый узел в коллекцию Nodes
                //С именем текущей директории и указанием ключа 
                //со значением "File".
                curNode.Nodes.Add("File", file.Name);

                //curNode.Nodes.Add("File", file.Name, 
                //тут можно указать номер картинки для узла из imageCollection);  
            }
        }
        #endregion *** TreeView ***

"Run" button “运行”按钮

 // Выполнить 
        private void button3_Click(object sender, EventArgs e)
        {            
            // Перебор выбранных узлов "treeView"
               TreeNodeCollection Nodes;
               Nodes = treeView1.Nodes;

               CheckTrueTreeNode(Nodes);
        }

Recruiting. 招聘。 treeview. 树视图。 CheckTrueTreeNode (TreeNodeCollection Nodes) CheckTrueTreeNode(TreeNodeCollection节点)

#region *** Рекруссия. treeView ***
        void CheckTrueTreeNode(TreeNodeCollection Nodes)
        {
                foreach (TreeNode tn in Nodes)
                {
                    if (tn.Checked == true)
                    {
                    // textBox1.Text += (tn.Name + " -**//**- " + path + tn.FullPath + "\r\n");  // инфо сообщение 
                    //treeView1.SelectedNode = null;
                    //treeView1.SelectedNode = tn;
                    //tn.EnsureVisible();
                    //return;

                    // путь к выбранному файлу 
                    pathFileData = path + tn.FullPath;

                    // BackgroundWorker. Старт
                    bw_start();

                    }

                    CheckTrueTreeNode(tn.Nodes);
                }
        }
        #endregion *** Рекруссия ***

Start "BackgroundWorker". 启动“ BackgroundWorker”。 bw_start () bw_start()

private void bw_start()
         {
                // bw = new BackgroundWorker[];                
                i++;

                //новый поток
                bw[i] = new BackgroundWorker();
                bw[i].WorkerReportsProgress = true;
                bw[i].WorkerSupportsCancellation = true;

                bw[i].DoWork += new DoWorkEventHandler(bw_DoWork); 
                bw[i].RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted); //обработчик 
                bw[i].ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

                if (bw[i].IsBusy != true)
                bw[i].RunWorkerAsync();
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
            {
                DataTable table_1;

                //привязка данных
                BindingSource bs;


                table_1 = new DataTable();
                table_1.Columns.Add("Content", typeof(string));
                table_1.Columns.Add("DateTime", typeof(DateTime));

                bs = new BindingSource(table_1, "");


                // Читаем файл "Данные"
                string[] lines = System.IO.File.ReadAllLines(pathFileData);

                // System.Console.WriteLine("Contents of WriteLines2.txt = ");
                foreach (string line in lines)
                {
                    // создаем новую запись
                    DataRow newrow = table_1.NewRow();

                    // заполняем ее данными
                    newrow["Content"] = line;
                    newrow["DateTime"] = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss");

                    // заносим запись в таблицу
                    table_1.Rows.Add(newrow);

                    // обновляем данные в грид
                    bs.ResetBindings(false);

                    // Пауза
                    System.Threading.Thread.Sleep(1500);
                    Application.DoEvents();
                }
            }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {

            }

        static void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {

            }

Paragraph: "While the program is executing the process of moving lines from the" Data "file to" DateTable ", the user can navigate the tree with the cursor. If the user enters the "Data" file for a process that has already been started, "GridUserControl" is displayed in "panel3" with the current state of filling "DateGrid" with " 段落:“程序正在执行将行从“数据”文件移动到“日期表”的过程时,用户可以使用光标浏览树。如果用户输入已经存在的过程的“数据”文件开始时,“ panel3”中会显示“ GridUserControl”,并以“

Provides 
// События TreeView/ Происходит после выбора узла дерева.
        private void TreeView1_AfterSelect(Object sender, TreeViewEventArgs e)
        {
            panel1.Controls.Clear();

            GridUserControl GridUsCont = new GridUserControl(????);

            panel1.Controls.Add(GridUsCont);

        }

* GridUserControl.cs * * GridUserControl.cs *

namespace TreeView_FolderTree
{
    public partial class GridUserControl : UserControl
    {

        public string pathFileData;

        public GridUserControl(string pathFileData)
        {
            InitializeComponent();

            // Обрабатываем данные
            //Или записываем их в поле
* *         this.pathFileData = pathFileData;

        }

        private void GridUserControl_Load(object sender, EventArgs e)
        {
            start_GridUserControl();
        }

        public void start_GridUserControl()
        {            
            // dataGridView1
            dataGridView1.DataSource = bs;
            dataGridView1.Columns["DateTime"].DefaultCellStyle.Format = "dd.MM.yyyy HH:mm:ss tt";            

        }


    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM