【问题标题】:I want to make a function that get the names of it caller for an array of radio buttons c#我想创建一个函数来获取它调用者的名称,以获取一组单选按钮 c#
【发布时间】:2021-06-11 02:50:09
【问题描述】:

我对 c# 和整体编程非常陌生。我的问题是我有一组单选按钮,其中包含程序已经知道的用户名称,我想要它,所以当用户单击它们时,该单选按钮的名称/文本出现在某个文本框中这是代码我用来制作单选按钮

foreach (string user in Registerd_Users)
        {
            string name = "Something it doesn't matter how this part works don't worry about it :)";
           
            buttonArray[i] = new RadioButton();
            buttonArray[i].Size = new Size(110, 21);
            buttonArray[i].Location = new Point(29, (44+(i*20)));
            buttonArray[i].Name = name;
            buttonArray[i].Text = name;
            this.Controls.Add(buttonArray[i]);
            i++;

所以如果有人可以向我解释如何解决这个问题,我很感激!

【问题讨论】:

    标签: c# arrays windows function radio-button


    【解决方案1】:

    您需要为每个 RB 的一些合适的事件添加一个处理程序,例如 CheckedChanged,当它发生时,如果 RB 已被选中,则设置文本框 Text,例如:

    buttonArray[i].CheckedChanged += (sender, e) =>
      { if(sender is RadioButton r && r.Checked) _someTextbox.Text = r.Text; }
    

    我们测试 rb 是否被检查,因为 CheckedChanged 也会在新的检查时为未检查的 RB 触发

    如果您正在寻找存储大量未显示在表单上的不同文本的位置,请在 r.Tag 中进行,而不是在 r.Text/r.Name 中进行

    【讨论】:

    • 感谢您的回答,因为我说我对编程很陌生。所以你能告诉我RadioButton r/r.Checked/....中的“r”是什么吗? @caius-jard
    • 这是单选按钮。过去在 c# 中,您为安全代码编写了两条语句:var r = sender as RadioButton; if(r != null && r.Checked) textbox.Text = r.Text;,但现在您可以执行 x is Type y 来测试 x 是否为 type ,然后进行强制转换,并将其存储在变量 y 中以便您可以使用它。如果您愿意,请使用旧方式:(sender, e) => if(((RadioButton)sender).Checked) textbox.Text = ((RadioButton)sender).Text; 只是有点混乱
    • @Charlieface 因为我想再次使用 r,两次,所以我使用 is 创建它,读取 Checked 然后读取 Text。看你上面的评论
    猜你喜欢
    • 1970-01-01
    • 2014-04-29
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多