【问题标题】:Search function for controls at run time在运行时搜索控件的功能
【发布时间】:2014-05-20 08:01:02
【问题描述】:

我有一个选项卡控件,我可以在其中添加由按钮和标签组成的自定义控件。我想在我的项目中添加一个搜索功能,以便当用户键入控件的名称时,它将显示名称(标签)以键入的字母开头的所有控件。在文本框中输入也可以完成这项工作。有没有简单的方法可以做到这一点?

【问题讨论】:

  • 这完全取决于您的应用架构和实现。您至少应该提供一些代码来展示您如何管理这些自定义控件,或者尝试创建某种搜索,然后您将获得如何改进它的建议。

标签: c# winforms search tabcontrol


【解决方案1】:

您可以在父控件集合中搜索控件:

 foreach(Control c in ParentControl.Controls)
 {
      if(c.Name == "label1")
      {
         //add to your list
      }
 }

您也可以使用StartsWith("stringVal")查看

     if(c.Name.StartsWith("l"))
     {
         //add to your list
     }

【讨论】:

    【解决方案2】:
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
       foreach (Control control in this.Controls)
       {
          // Skip, if the control is the used TextBox
          if (control == textBox1) { continue; }
    
          // Show all controls where name starts with inputed string
          // (use ToLower(), so casing doesnt matter)
          if (control.Name.ToLower().StartsWith(textBox1.Text.Trim().ToLower()))
          {
             control.Visible = true;
          }
    
          // Hide objects that doesn't match
          else { control.Visible = false; }
       }
    }
    

    这会切换控件的可见性,并隐藏与给定输入不匹配的所有项目。大小写也无关紧要。

    【讨论】:

      【解决方案3】:

      在文本框中添加要搜索的文本时完成。

       private void textBox1_TextChanged(object sender, EventArgs e)
           {
              foreach (Control c in fl_panel.Controls)
              {              
                  if (c.Name.ToUpper().StartsWith(textBox1.Text.ToUpper().ToString()) && textBox1.Text != "")
                  {
                      Control[] ctrls = fl_panel.Controls.Find(textBox1.Text.ToString(), true);
                      c.Visible = true;  // to restore previous matches if I delete some text
                  }
      
                  else if(textBox1.Text == "")
                  {
                      c.Visible = true;
                  }
                  else
                  {
                      c.Visible = false;
                  }                      
              }
          }
      

      【讨论】:

        【解决方案4】:

        你可以试试这个来找到与文本框中输入的文本匹配的控件,然后你可以用它做任何你想做的事情。

             private void textBox1_TextChanged(object sender, EventArgs e)
         {
        
            var controlMatchesCriteria = from c in this.Controls.OfType<TextBox>()
                    where c.Name == textBox1.Text
                    select c;
        }
        

        【讨论】:

          猜你喜欢
          • 2011-05-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多