【问题标题】:How to select all text boxes with a specific tag如何选择具有特定标签的所有文本框
【发布时间】:2016-12-04 20:56:13
【问题描述】:

使用 c# 6 windows 窗体,我想选择所有带有“txt”标签的文本框。 我已经确认其中有几个带有“txt”标签。然后,我想清除文本。但是下面的代码没有选择任何。

this.Controls.OfType<TextBox>()
             .Where(textBox => textBox.Tag.ToString() == "txt").ToList()
             .ForEach(textBox => textBox.Clear());

【问题讨论】:

  • 也许它们不是Form 的直接子级,而您将它们放置在其他一些容器控件中。 - 还要注意可能的NullReferenceException 这里textBox.Tag.ToString()
  • this是什么类型的控件?
  • 我在 GroupBoxes -> foreach (var textBox in Controls.OfType().Where(textBox => textBox.Tag?.ToString() == "txt ").SelectMany(groupBox => groupBox.Controls.OfType())) { textBox.Clear(); }
  • 它们是文本框

标签: c# .net winforms linq


【解决方案1】:

你的代码几乎可以工作,使用这个:

        this.Controls.OfType<TextBox>()
            .Where(text =>!(text.Tag == null) && text.Tag.ToString() == "txt").ToList()
            .ForEach(text => text.Clear());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-27
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    相关资源
    最近更新 更多