【问题标题】:Is there a way to control all radio buttons through one control? Instead of passing a control for each radio button (C#)有没有办法通过一个控件来控制所有单选按钮?而不是为每个单选按钮传递一个控件(C#)
【发布时间】:2017-09-21 17:35:20
【问题描述】:

我目前正在用 c# 在 winform 上创建一个在线商店。

目前我正在创建一个与“购物篮”相关的文本框,如果用户单击特定单选按钮,文本框会在文本框中显示产品描述。

我已将我的单选按钮分组到一个组框中,并想知道是否有任何等效于所有单选按钮的 'SelectedIndex' 命令?谢谢。

【问题讨论】:

  • 为所有单选按钮订阅相同的CheckedChanged 事件。
  • @DangerZone 你能举个例子吗? p.s.一次可以选择多个单选按钮。谢谢!
  • 如果一次可以选择多个,则不应将它们一起包含在同一个组框中。请改用复选框。
  • 查看 Windows 窗体的 RadioButtonList。它实际上是一个ListBox,其项目呈现为单选按钮。所以你可以使用它的DataSourceDisplayMemberValueMemberSelectedIndexSelectedItem等等。
  • @RezaAghaei RadioButtonList 可以在 winforms 中使用吗?

标签: c# winforms radio-button groupbox selectedindex


【解决方案1】:

只需为所有单选按钮订阅同一个事件。然后,您可以对已检查的内容采取行动并采取相应的行动,而不是为每个按钮设置重复的代码。
下面是一个简单的示例,它将文本框的Text 属性设置为显示已选中。

表单类

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void radioButtons_CheckedChanged(object sender, EventArgs e)
    {
        //Do whatever you need to do here. I'm simple setting some text based off
        //the name of the checked radio button.

        System.Windows.Forms.RadioButton rb = (sender as System.Windows.Forms.RadioButton);
        textBox1.Text = $"{rb.Name} is checked!";
    }
}

在 .designer.cs 文件中

//Note that the EventHandler for each is the same.
this.radioButton3.CheckedChanged += new System.EventHandler(this.radioButtons_CheckedChanged);
this.radioButton2.CheckedChanged += new System.EventHandler(this.radioButtons_CheckedChanged);
this.radioButton1.CheckedChanged += new System.EventHandler(this.radioButtons_CheckedChanged);

【讨论】:

  • 这可行,有没有一种方法可以让文本框中的值以列表的形式出现?所以用户点击说 3 个单选按钮,这会在文本框中创建一个包含 3 个产品的列表?我觉得好像我可能把这个复杂化了,所以如果没有其他方法,我将不得不考虑使用按钮。谢谢!
  • @TheBiz - 首先,就像我在对问题本身的评论中提到的那样,如果可以选择多个,请选择单选按钮以外的其他内容。如果它们位于表单上的同一区域,则它们一次只能选择 1 个。否则复选框是更好的用户体验。但是要回答您的问题,是的,只需将文本框设为多行,然后根据检查的内容构建文本。
  • 好的,这对我来说非常有效,因为我已经对产品进行了分类,因此单选按钮可以有效地工作。但是,我使用了您的代码以及我自己的一些代码,它们确实在文本框中输入了一个值,但它显示的是“设计名称”而不是实际产品。我已经使用类来定义我的产品,我将如何输入这个,所以当我单击单选按钮时,它会显示产品而不是按钮的设计名称?谢谢(对不起,如果这是一个非常简单的问题)
  • @TheBiz 如果产品是单选按钮的文本,只需使用.Text 属性而不是.Name
【解决方案2】:

如果您希望一次能够选择多个单选按钮,我建议您使用复选框而不是单选按钮。您可以将他们的所有事件分配给同一个事件并控制选中哪些复选框。

    private void checkBox_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox checkBoxControl = (CheckBox) sender; // You can use this variable to see which one of the checkbox is checked.
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多