ComboBox 和 TextBox 功能相同

ComboBox and TextBox with Same Functions

大家好,我想知道有没有可能

Winform 项目

A.) 1~5组合框

B.) 1~5 个时间文本框(例如我将它们标识为 txtTime1 ~ txtTime5)

C.) 1~5 金额文本框(例如我将它们标识为 txtAmount1 ~ txtAmount5)

项目 1 ~ 5(ComboBox 1-5,txtTime 1-5,txtAmount 1-5)将执行相同的功能。

A.)

if (combobox1.SelectedValue.ToString() == "Regular")
    {
        x = 1.25;
    }
else if (combobox1.SelectedValue.ToString() == "Double")
    {
        x = 2;
    }
 // Same Codes for ComboBox 2~5

B.)Textbox "txtTime(s)" 将持有一个 TextChange 事件来获取我们所说的 comboBoxes

的值
if (txtTime.Text.Lenght > 0)
    {
    // Item Letter "C"
    // value of "x" is equal to the above item
    txtAmount.Text = (double.Parse(txtTime.Text) * x).ToString();
    }

我只是想快速了解一下我将如何完成这项工作

提前致谢

编辑*

我能想到的就是一个接一个地称呼他们只是一个快速代码

private Method1()
{ double x,base;
  if (combobox1 = "Regular")
    { x = base * 1.25; }

  if (combobox2 = "Regular")
    { x = base * 1.25; }
      // so on
 return x;
}

private txtTime1_TextChange(Event ****)
  { 
    if (txtTime1.Text.Lenght > 0)
      { txtAmount1.Text = (Method1() * double.Parse(txtTime1.Text)).ToString();}


private txtTime2_TextChange(Event ****)
    { 
     if (txtTime2.Text.Lenght > 0)
      { txtAmount2.Text = (Method1() * double.Parse(txtTime2.Text)).ToString();}

    // and so on

您可以使用一个方法作为您的控件事件处理程序。每个事件处理程序都有一个 sender 参数,代表触发事件的控件。 您可以拥有这样的事件处理程序:

public ComboBoxEventHandler(object sender,EventArgs args)
{
var comboBox=sender as ComboBox;
if(comboBox==null) return;
if (comboBox.SelectedValue.ToString() == "Regular")
    {
        x = 1.25;
    }
else if (comboBox.SelectedValue.ToString() == "Double")
    {
        x = 2;
    }
}}

您可以对其他控件执行相同的操作。

更新

为了使事情更容易维护,您可以拥有一个包含相应控件及其行为的 class,然后您可以将控件动态添加到您的表单中,而无需重复您自己的操作,或者您可以向您的表单中添加更多行很容易形成。以这样的事情为例:

public class RowController
{
public ComboBox Rate{get;private set;}
public TextBox Hours{get;private set;}
public TextBox Amount{get;private set;}

public RowController(ComboBox rate,TextBox hours,TextBox amount)
{
Rate=rate;
Hours=hours;
Hours.TextChange+=OnHoursChanged;
Amount=amount;
}

private void OnHoursChanged(object sender,EventArgs args)
{
 if (Hours.Text.Length > 0)
      { Amount.Text = (GetRate() * double.Parse(Hours.Text)).ToString();}
}

private double GetRate()
{
if (Rate.SelectedValue.ToString() == "Regular")
    {
        return 1.25;
    }
else if (Rate.SelectedValue.ToString() == "Double")
    {
        return 2;
    }
}
}

然后您可以像这样在表单中定义 RowControllers :

var row1=new RowController(comboBox1,txtTime1,txtAmount1);

并且每个控制器将各自完成自己的工作。