如何获取要在现有文本文件中列出的单选按钮的名称/文本?
Posted
技术标签:
【中文标题】如何获取要在现有文本文件中列出的单选按钮的名称/文本?【英文标题】: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您可以使用OfType<..>
指定所需的控件类型。这将返回经过过滤的控件集合,转换为指定类型。
foreach (RadioButton rb in this.Controls.OfType<RadioButton>())
Similar question found here
您需要导入 Linq 才能使用此扩展方法。
using System.Linq;
【讨论】:
以上是关于如何获取要在现有文本文件中列出的单选按钮的名称/文本?的主要内容,如果未能解决你的问题,请参考以下文章