按钮从组合框获取数据 - Visual Studio

本文关键字:Visual Studio 数据 获取 组合 按钮 | 更新日期: 2023-09-27 18:36:58

我正在尝试将按钮更改为组合框。 原始代码如下

private void btnSign_Click(object sender, EventArgs e)
    {
        stopWatch = Stopwatch.StartNew();
        record = true;
        redOrGreen = new Bgr(Color.LightGreen);
        if (sender == btnSign1)
            recordSign = 1;
        else if (sender == btnSign2)
            recordSign = 2;
        else if (sender == btnSign3)
            recordSign = 3;
        else if (sender == btnSign4)
            recordSign = 4;
        else if (sender == btnSign5)
            recordSign = 5;
        else
            recordSign = 6;
    }

在 if-else 语句中,有我最初拥有的按钮,我想将这些 btnSign 替换为组合框。

有什么解决办法吗?

按钮从组合框获取数据 - Visual Studio

使用项列表填充组合框,并使用选定的项属性来驱动逻辑。下面是一个示例:

using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
  public class RecordSign
  {
    public int recordSign { get; set; }
    public string Description { get; set; }
  }
  public partial class Form1 : Form
  {
    int recordSign = 0;
    public Form1()
    {
      InitializeComponent();
      comboBox1.Items.Add(new RecordSign() { recordSign = 1, Description = "Record Sign 1" });
      comboBox1.Items.Add(new RecordSign() { recordSign = 2, Description = "Record Sign 2" });
      comboBox1.Items.Add(new RecordSign() { recordSign = 3, Description = "Record Sign 3" });
      comboBox1.Items.Add(new RecordSign() { recordSign = 4, Description = "Record Sign 4" });
      comboBox1.Items.Add(new RecordSign() { recordSign = 5, Description = "Record Sign 5" });
      comboBox1.Items.Add(new RecordSign() { recordSign = 6, Description = "Record Sign 6" });
      //Show the user-friendly text in the combobox
      comboBox1.DisplayMember = "Description";
      //Use the underlying value of the selected object for code logic
      comboBox1.ValueMember = "recordSign";
    }
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
      //SelectedValue is an [object] so cast it to the type you need.
      var theRecordSign = comboBox1.SelectedItem as RecordSign;
      label1.Text = string.Format(
        "The chosen item is {0}, and its value is {1}.",
        theRecordSign.Description, theRecordSign.recordSign);
      recordSign = theRecordSign.recordSign;
    }
  }
}