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

问题描述:

在Form1顶部:如何从另一个用户控件访问form1上的label4?

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

然后在用户控制

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 
      } 
     } 

但是,当我尝试访问它LabelText的是不存在的。 如果我将使form1的新实例不会重新创建form1构造函数?

我想从用户控件更新label4。

这是完整的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; 
     } 
    } 
} 

这是完整的用户控件的代码,我不认为它会在启动需要:

如果我将添加一个参数类型标签在这里:

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

我添加参数标签为textLabel 那么我就行收到错误:

fileListDelegate = new FileListDelegate(AddFiles); 

没有重载 'AddFiles' 匹配委托 'DirectorySearcher.FileListDelegate'

这是用户控件的代码完成:

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 }); 
      } 
     } 
    } 
} 

而且Form1设计:

命名空间Search_files { partial class Form1 { /// ///必填de签名变量。 /// private 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; 
} 

}

+0

你甚至试图访问'.LabelText' ...?我只看到'Form1.Label'这听起来像表单的名称,而不是实例,但无论 – EpicKip

+0

@EpicKip在用户控件部分,我开始键入:Form1.Label .....它应该是Form1.LabelText,但是它不存在,所以我没有继续。 –

+0

下一次只要完成代码即使它不起作用,然后我们看到它出错的地方。但Form1听起来像类而不是实例 – EpicKip

牌标签作为paremeter到您的用户控件

 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 = ""; 
      } 
     } 

或设置属性一样

public Label TextLabel{ get; set;} 

然后在你的表格InitializeComponents()后做UserControl.TextLabel = myLabel;

+0

我将完整的用户控制代码添加到我的问题中,因为如果我将一个参数添加到AddFiles我得到错误的行fileListDelegate = new FileListDelegate(AddFiles); 'AddFiles'没有过载匹配委托'DirectorySearcher.FileListDelegate' –

+0

@HenAvrami这意味着参数不匹配。您是否已将'Label textLabel'作为参数添加到'DirectorySearcher.FileListDelegate'? – EpicKip