简体   繁体   中英

Store an integer based on a string from a combo box selection in C#

What I'm trying to do here is to select a string in comboBox1 and comboBox2, have an integer that is entered into to textBox1 multiplied by a specific number based on the selections made in the comboBoxs and then output the results of that multiplication to another read-only textbox.

comboBox1 has:
if comboBox1 = "Alpha" use integer 170
if comboBox1 = "Bravo" use integer 185
if comboBox1 = "Charlie" use integer 195
if comboBox1 = "Delta" use integer 225

& comboBox2 has:
if comboBox2 = "New" add 0 to the integer value determined in comboBox1
comboBox2 = "Old" add 25 to the integer value determined in comboBox1

Multiply a user defined integer entered in textBox1 by the sum value determined above and output that integer into the read-only textBox.

Any help is greatly appreciated!

I would either use a Tuple<string, int> or a class for the items in the list. Maybe something like:

class CBItem
{
    public string Text { get; private set; }
    public int Value { get; private set; }

    public CBItem(string text, int value)
    {
        Text = text;
        Value = value;
    }

    // This will determine what you see in the combobox
    public override string ToString()
    {
        return Text ?? base.ToString();
    }
}

Then you can add a bunch of CBItem s to your combobox instead of just strings:

comboBox1.Items.Add(new CBItem("Alpha", 170));
comboBox1.Items.Add(new CBItem("Bravo", 185));
comboBox1.Items.Add(new CBItem("Charlie", 195));
comboBox1.Items.Add(new CBItem("Delta", 225));

comboBox2.Items.Add(new CBItem("New", 0));
comboBox2.Items.Add(new CBItem("Old", 25));

And then in your handler, you can just cast SelectedItem to type CBItem.

CBItem cb1Item = (CBItem)comboBox1.SelectedItem;
CBItem cb2Item = (CBItem)comboBox2.SelectedItem;

int sum = cb1Item.Value + cb2Item.Value;

You can figure out how to multiply that sum by the value entered in the textbox from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM