使用"组合框选择更改"更改浮点值

时间:2017-01-30 18:56:49

标签: c# if-statement combobox

我正在尝试通过带有if语句的组合框更改Float值。

我不必是if语句,但我认为这是解决这个问题最合乎逻辑的方法。

但是当我尝试使用组合框中所选更改的if语句更改浮点数时,我得到了命名空间错误和定义错误......

我希望它稍后在程序中反映一个公式,在范围之外,因此浮点数会根据他们在下拉列表中选择的内容而改变。

我的" IF"声明

public void cmbSubClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSubClass.SelectedIndex == 1)
            {

               public float a = 0.86F; 
               public float b = 0.61F;
               public float c = 1.86F;  
            }
            if (cmbSubClass.SelectedIndex == 2)
            {
               public float a = 0.64F;
               public float b = 0.75F;
               public float c = 1.42F; 
            }
        }

公式的一个例子:

float zFormula = (a * val1) + (b * val2) + (c * val3)
textbox1.Text = Convert.ToString(zFormula);

我试图用课堂复制相同的东西,但我似乎无法弄清楚如何这样做。

2 个答案:

答案 0 :(得分:1)

可能是这样的(使用绑定):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        List<Data> data = new List<Data>();
        data.Add(new Data("Set1", 1, 2, 3));
        data.Add(new Data("Set2", 3, 2, 3));
        comboBox1.DataSource = data;
        comboBox1.DisplayMember = "Name";
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var set = comboBox1.SelectedValue as Data;
        var val1 = 1;
        float zFormula = (set.A * val1) + (set.B * val1) + (set.C * val1);
        textbox1.Text = Convert.ToString(zFormula);
    }
}

public class Data
{
    public Data(string name, float a, float b, float c)
    {
        Name = name;
        A = a; B = b; C = c;
    }

    public string Name { get; protected set; }
    public float A { get; protected set; }
    public float B { get; protected set; }
    public float C { get; protected set; }
}

答案 1 :(得分:0)

  

声明和设置变量是两回事。

在@LarsTech说......

后,它变得非常有意义
        public float a;
        public float b;
        public float c;
        public float d;
        public float f;

        public void cmbSubClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSubClass.SelectedIndex == 0)
            {
                txtOutput.Text = ("class1 selected");
                a = 1.12F;
                b = 2.32F;
                c = 3.32F;
                d = 4.31F;
                f = 5.23F;

            }
            if (cmbSubClass.SelectedIndex == 1)
            {
                txtOutput.Text = ("class2 selected");
                a = 0.01F;
                b = 0.21F;
                c = 0.23F;
                d = 0.75F;
                f = 1.66F;
            }
            if (cmbSubClass.SelectedIndex == 2)
            {
                txtOutput.Text = ("class3 selected");
                a = 1.02F;
                b = 1.22F;
                c = 1.42F;
                d = 1.62F;
                f = 1.32F;

            }
        }

问题解决了。