简体   繁体   English

如何从另一个用户控件访问 form1 上的 label4?

[英]How can i access label4 on form1 from another user control?

In Form1 top:在 Form1 顶部:

public String LabelText
{
   get { return label4.Text; }
   set { label4.Text = value; }
}

Then in the User Control然后在用户控件中

public int countf = 0;
        private void AddFiles(string[] files, int startIndex, int count)
        {
            while (count-- > 0)
            {
                countf++;
                listBox.Items.Add(files[startIndex + count]);
                Form1.Label
            }
        }

But LabelText is not existing when i try to access it.但是当我尝试访问它时 LabelText 不存在。 If i will make new instance of form1 won't it make over again the form1 constructor ?如果我要创建 form1 的新实例,它会不会重新创建 form1 构造函数?

I want to update label4 from the User Control.我想从用户控件更新 label4。

This is the complete Form1 code:这是完整的 Form1 代码:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace Search_files
{
    public partial class Form1 : Form
    {
        private DirectorySearcher directorySearcher;
        private System.Windows.Forms.TextBox searchText;
        private System.Windows.Forms.Label searchLabel;
        private System.Windows.Forms.Button searchButton;

        public String LabelText
        {
            get { return label4.Text; }
            set { label4.Text = value; }
        }

        public Form1()
        {
            //  
            // Required for Windows Forms designer support.  
            //  
            InitializeComponent();

            //  
            // Add any constructor code after InitializeComponent call here.  
            //  
        } 

        private void searchButton_Click(object sender, System.EventArgs e)
        {
            directorySearcher.SearchCriteria = searchText.Text;
            searchLabel.Text = "Searching...";
            directorySearcher.BeginSearch();
        }

        private void directorySearcher_SearchComplete(object sender, System.EventArgs e)
        {
            searchLabel.Text = string.Empty;
        }
    }
}

This is the complete User Control code i didn't think it would be needed in the start:这是完整的用户控制代码,我认为一开始不需要它:

If i will add a parameter type Label here:如果我将在这里添加一个参数类型标签:

private void AddFiles(string[] files, int startIndex, int count, Label textlabel)
        {
            while (count-- > 0)
            {
                countf++;
                listBox.Items.Add(files[startIndex + count]);
            }
        }

I added the parameter Label textlabel Then i'm getting error on the line:我添加了参数 Label textlabel 然后我在线上收到错误:

fileListDelegate = new FileListDelegate(AddFiles);

No overload for 'AddFiles' matches delegate 'DirectorySearcher.FileListDelegate' “AddFiles”没有重载匹配委托“DirectorySearcher.FileListDelegate”

This is the completed code of the User Control:这是用户控件的完整代码:

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

namespace Search_files
{
    public partial class DirectorySearcher : UserControl
    {
        // Define a special delegate that handles marshaling  
        // lists of file names from the background directory search  
        // thread to the thread that contains the list box.  
        private delegate void FileListDelegate(string[] files, int startIndex, int count);

        private ListBox listBox;
        private string searchCriteria;
        private bool searching;
        private bool deferSearch;
        private Thread searchThread;
        private FileListDelegate fileListDelegate;
        private EventHandler onSearchComplete;

        public DirectorySearcher()
        {
            listBox = new ListBox();
            listBox.Dock = DockStyle.Fill;

            Controls.Add(listBox);

            fileListDelegate = new FileListDelegate(AddFiles);
            onSearchComplete = new EventHandler(OnSearchComplete);
        }

        public string SearchCriteria
        {
            get
            {
                return searchCriteria;
            }
            set
            {
                // If currently searching, abort  
                // the search and restart it after  
                // setting the new criteria.  
                //  
                bool wasSearching = Searching;

                if (wasSearching)
                {
                    StopSearch();
                }

                listBox.Items.Clear();
                searchCriteria = value;

                if (wasSearching)
                {
                    BeginSearch();
                }
            }
        }

        public bool Searching
        {
            get
            {
                return searching;
            }
        }

        public event EventHandler SearchComplete;

        /// <summary>  
        /// This method is called from the background thread. It is called through  
        /// a BeginInvoke call so that it is always marshaled to the thread that  
        /// owns the list box control.  
        /// </summary>  
        /// <param name="files"></param>  
        /// <param name="startIndex"></param>  
        /// <param name="count"></param>
        /// 
        public int countf = 0;
        private void AddFiles(string[] files, int startIndex, int count, Label textlabel)
        {
            while (count-- > 0)
            {
                countf++;
                listBox.Items.Add(files[startIndex + count]);
            }
        }

        public void BeginSearch()
        {
            // Create the search thread, which   
            // will begin the search.  
            // If already searching, do nothing.  
            //  
            if (Searching)
            {
                return;
            }

            // Start the search if the handle has  
            // been created. Otherwise, defer it until the  
            // handle has been created.  
            if (IsHandleCreated)
            {
                searchThread = new Thread(new ThreadStart(ThreadProcedure));
                searching = true;
                searchThread.Start();
            }
            else
            {
                deferSearch = true;
            }
        }

        protected override void OnHandleDestroyed(EventArgs e)
        {
            // If the handle is being destroyed and you are not  
            // recreating it, then abort the search.  
            if (!RecreatingHandle)
            {
                StopSearch();
            }
            base.OnHandleDestroyed(e);
        }

        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            if (deferSearch)
            {
                deferSearch = false;
                BeginSearch();
            }
        }

        /// <summary>  
        /// This method is called by the background thread when it has finished  
        /// the search.  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void OnSearchComplete(object sender, EventArgs e)
        {
            if (SearchComplete != null)
            {
                SearchComplete(sender, e);
            }
        }

        public void StopSearch()
        {
            if (!searching)
            {
                return;
            }

            if (searchThread.IsAlive)
            {
                searchThread.Abort();
                searchThread.Join();
            }

            searchThread = null;
            searching = false;
        }

        /// <summary>  
        /// Recurses the given path, adding all files on that path to   
        /// the list box. After it finishes with the files, it  
        /// calls itself once for each directory on the path.  
        /// </summary>  
        /// <param name="searchPath"></param>  
        private void RecurseDirectory(string searchPath)
        {
            // Split searchPath into a directory and a wildcard specification.  
            //  
            string directory = Path.GetDirectoryName(searchPath);
            string search = Path.GetFileName(searchPath);

            // If a directory or search criteria are not specified, then return.  
            //  
            if (directory == null || search == null)
            {
                return;
            }

            string[] files;

            // File systems like NTFS that have  
            // access permissions might result in exceptions  
            // when looking into directories without permission.  
            // Catch those exceptions and return.  
            try
            {
                files = Directory.GetFiles(directory, search);
            }
            catch (UnauthorizedAccessException)
            {
                return;
            }
            catch (DirectoryNotFoundException)
            {
                return;
            }

            // Perform a BeginInvoke call to the list box  
            // in order to marshal to the correct thread. It is not  
            // very efficient to perform this marshal once for every  
            // file, so batch up multiple file calls into one  
            // marshal invocation.  
            int startingIndex = 0;

            while (startingIndex < files.Length)
            {
                // Batch up 20 files at once, unless at the  
                // end.  
                //  
                int count = 20;
                if (count + startingIndex >= files.Length)
                {
                    count = files.Length - startingIndex;
                }

                // Begin the cross-thread call. Because you are passing  
                // immutable objects into this invoke method, you do not have to  
                // wait for it to finish. If these were complex objects, you would  
                // have to either create new instances of them or   
                // wait for the thread to process this invoke before modifying  
                // the objects.  
                IAsyncResult r = BeginInvoke(fileListDelegate, new object[] { files, startingIndex, count });
                startingIndex += count;
            }

            // Now that you have finished the files in this directory, recurse for  
            // each subdirectory.  
            string[] directories = Directory.GetDirectories(directory);
            foreach (string d in directories)
            {
                RecurseDirectory(Path.Combine(d, search));
            }
        }

        /// <summary>  
        /// This is the actual thread procedure. This method runs in a background  
        /// thread to scan directories. When finished, it simply exits.  
        /// </summary>  
        private void ThreadProcedure()
        {
            // Get the search string. Individual   
            // field assigns are atomic in .NET, so you do not  
            // need to use any thread synchronization to grab  
            // the string value here.  
            try
            {
                string localSearch = SearchCriteria;

                // Now, search the file system.  
                //  
                RecurseDirectory(localSearch);
            }
            finally
            {
                // You are done with the search, so update.  
                //  
                searching = false;

                // Raise an event that notifies the user that  
                // the search has terminated.    
                // You do not have to do this through a marshaled call, but  
                // marshaling is recommended for the following reason:  
                // Users of this control do not know that it is  
                // multithreaded, so they expect its events to   
                // come back on the same thread as the control.  
                BeginInvoke(onSearchComplete, new object[] { this, EventArgs.Empty });
            }
        }
    }
}

And the form1 designer:和 form1 设计师:

namespace Search_files { partial class Form1 { /// /// Required designer variable. namespace Search_files { partial class Form1 { /// /// 必需的设计器变量。 /// private System.ComponentModel.IContainer components = null; /// 私有 System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.searchButton = new System.Windows.Forms.Button();
        this.searchText = new System.Windows.Forms.TextBox();
        this.searchLabel = new System.Windows.Forms.Label();
        this.label3 = new System.Windows.Forms.Label();
        this.label4 = new System.Windows.Forms.Label();
        this.directorySearcher = new Search_in_files.DirectorySearcher();
        this.SuspendLayout();
        // 
        // searchButton
        // 
        this.searchButton.Location = new System.Drawing.Point(8, 16);
        this.searchButton.Name = "searchButton";
        this.searchButton.Size = new System.Drawing.Size(88, 40);
        this.searchButton.TabIndex = 0;
        this.searchButton.Text = "&Search";
        this.searchButton.Click += new System.EventHandler(this.searchButton_Click);
        // 
        // searchText
        // 
        this.searchText.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.searchText.Location = new System.Drawing.Point(104, 24);
        this.searchText.Name = "searchText";
        this.searchText.Size = new System.Drawing.Size(378, 20);
        this.searchText.TabIndex = 1;
        this.searchText.Text = "c:\\*.cs";
        // 
        // searchLabel
        // 
        this.searchLabel.ForeColor = System.Drawing.Color.Red;
        this.searchLabel.Location = new System.Drawing.Point(104, 48);
        this.searchLabel.Name = "searchLabel";
        this.searchLabel.Size = new System.Drawing.Size(176, 16);
        this.searchLabel.TabIndex = 3;
        // 
        // label3
        // 
        this.label3.AutoSize = true;
        this.label3.Location = new System.Drawing.Point(299, 51);
        this.label3.Name = "label3";
        this.label3.Size = new System.Drawing.Size(80, 13);
        this.label3.TabIndex = 4;
        this.label3.Text = "Number of files ";
        // 
        // label4
        // 
        this.label4.AutoSize = true;
        this.label4.Location = new System.Drawing.Point(385, 51);
        this.label4.Name = "label4";
        this.label4.Size = new System.Drawing.Size(35, 13);
        this.label4.TabIndex = 5;
        this.label4.Text = "label4";
        // 
        // directorySearcher
        // 
        this.directorySearcher.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.directorySearcher.Location = new System.Drawing.Point(8, 72);
        this.directorySearcher.Name = "directorySearcher";
        this.directorySearcher.SearchCriteria = null;
        this.directorySearcher.Size = new System.Drawing.Size(474, 200);
        this.directorySearcher.TabIndex = 2;
        this.directorySearcher.SearchComplete += new System.EventHandler(this.directorySearcher_SearchComplete);
        // 
        // Form1
        // 
        this.ClientSize = new System.Drawing.Size(494, 291);
        this.Controls.Add(this.label4);
        this.Controls.Add(this.label3);
        this.Controls.Add(this.searchLabel);
        this.Controls.Add(this.directorySearcher);
        this.Controls.Add(this.searchText);
        this.Controls.Add(this.searchButton);
        this.Name = "Form1";
        this.Text = "Search Directories";
        this.ResumeLayout(false);
        this.PerformLayout();

    }

    #endregion

    private System.Windows.Forms.TextBox textBox1;
    private System.ComponentModel.BackgroundWorker backgroundWorker1;
    private ListViewCostumControl listViewCostumControl1;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.Label label4;
}

} }

Pass label as a paremeter to your UserControl将标签作为参数传递给您的 UserControl

        public int countf = 0;
        public void AddFiles(string[] files, int startIndex, int count, Label textLabel)
        {
            while (count-- > 0)
            {
                countf++;
                listBox.Items.Add(files[startIndex + count]);
                textLabel.Text = "";
            }
        }

or set it property like或将其设置为属性

public Label TextLabel{ get; set;}

Then in your Form after InitializeComponents() do UserControl.TextLabel = myLabel;然后在您的 Form 之后InitializeComponents()UserControl.TextLabel = myLabel;

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

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