【问题标题】:How do I get the name/text of a radio button to be listed in an existing text file?如何获取要在现有文本文件中列出的单选按钮的名称/文本?
【发布时间】:2022-01-13 21:20:55
【问题描述】:

(文本文件以单独的形式创建)

这是我目前所拥有的:

foreach (RadioButton rb in this.Controls)
            if (rb.Checked)
            {
                StreamWriter details;
                details = File.AppendText("User Details.txt");
                details.WriteLine("Preferences:" + rb.Text);
                
                 }

运行时显示:System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Forms.TextBox' to type 'System.Windows.Forms.RadioButton'。'

【问题讨论】:

  • 我相信您需要将 Controls 集合过滤为您期望的类型。使用 System.Linq; foreach(Controls.OfType 中的 RadioButton())
  • 不要推出自己的偏好系统;已经有一个非常好的内置在 winforms 中

标签: c# winforms


【解决方案1】:

您可以使用OfType<..> 指定所需的控件类型。这将返回经过过滤的控件集合,转换为指定类型。

foreach (RadioButton rb in this.Controls.OfType<RadioButton>())

Similar question found here

您需要导入 Linq 才能使用此扩展方法。

using System.Linq;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 2017-08-26
    相关资源
    最近更新 更多