【问题标题】:Capture name on a radio button?在单选按钮上捕获名称?
【发布时间】:2019-11-26 02:42:01
【问题描述】:

作为编码的大新手,我如何使以下部分正常工作? 我想捕获RadioButtonText

例如

radio1.Text = weekly

radio2.Text = monthly

// Doesn't compile; to show the requirement only
if (radio1.checked) then 3
  write weekly
else if (radio2.checked) then 
  write monthly

// write to txt file 
var line = string.Join(Environment.NewLine,
  $"First Name:               {tfirstn.Text}",
  $"Last Name:                {tlastn.Text}",
  $"Address:                  {taddr.Text}",
  $"Mobile Number:            {tmobi.Text}",
  $"Recurring Payment Amount: {rpabox.Text}",
  $"Account Number:           {taccnbr.Text}",
   // this should display "weekly" or "monthly" depending on radio button checked
  $"Frequency:                {}", 
  $"",
  $"",
   ""
);

【问题讨论】:

标签: c# winforms


【解决方案1】:

假设 所有 感兴趣的单选按钮在 same 容器中,例如myPanel,你可以试试Linq:在容器中的所有RadioButtons中(DailyWeeklyMonthlyYearly等),让我们找到取出First 一个Checked,取其Text(如果所有RadioButtons 都未选中,则返回"???"

using System.Linq;

...

radio1.Text = "Weekly";
radio2.Text = "Monthly";

...

string frequency = myPanel // put "this" if radiobuttons are on the form
  .Controls
  .OfType<RadioButton>()
  .FirstOrDefault(rb => rb.Checked)
 ?.Text ?? "???"; // "???" - if none radiobutton is checked

...

var line = string.Join(Environment.NewLine,
  ...
  $"Frequency:                {frequency}", // this should display Weekly or Monthly  
  ...
);

【讨论】:

    【解决方案2】:

    试试这个:

    radio1.Checked ? "weekly" : "monthly"
    

    upd:让答案更清楚

    var line = string.Join(Environment.NewLine,
                  $"First Name:               {tfirstn.Text}",
                  $"Last Name:                {tlastn.Text}",
                  $"Address:                  {taddr.Text}",
                  $"Mobile Number:            {tmobi.Text}",
                  $"Recurring Payment Amount: {rpabox.Text}",
                  $"Account Number:           {taccnbr.Text}",
                  "Frequency:"              + radio1.Checked ? "weekly" : "monthly",
                  $"",
                  $"",
                   ""
                );
    

    如果选择了 radio1,则打印“weekly”,如果选择了 radio2,则打印“monthly”或未选择任何电台

    【讨论】:

    • 如果两者都没有检查怎么办?
    • 从问题中不清楚,如果其中一个被选中。但只有2例出现。假设之前在代码中没有对此进行检查,默认值是“每月”,如果我们使用我上面的代码,则在没有检查无线电的情况下
    • 通过这样做我得到:缺少关闭分隔符,意外令牌,语法错误
    • 编辑了我的答案。似乎字符串插值不会那样表达,但简单的 concat 应该可以工作
    • 还是不行,如果你要重写代码你会怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    相关资源
    最近更新 更多