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

时间:2015-01-10 14:58:24

标签: c# visual-studio-2013 combobox

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

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替换为组合框。

任何解决方案?

1 个答案:

答案 0 :(得分:0)

使用项列表填充组合框,并使用所选的项属性来驱动逻辑。这是一个例子:

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;

    }
  }
}