【问题标题】:Store an integer based on a string from a combo box selection in C#根据 C# 中组合框选择中的字符串存储整数
【发布时间】:2014-07-26 01:46:57
【问题描述】:

我在这里要做的是在comboBox1和comboBox2中选择一个字符串,将输入到textBox1的整数乘以基于在comboBoxs中所做选择的特定数字,然后输出结果乘法到另一个只读文本框。

comboBox1 有:
如果 comboBox1 = "Alpha" 使用整数 170
如果 comboBox1 = "Bravo" 使用整数 185
如果 comboBox1 = "Charlie" 使用整数 195
如果 comboBox1 = "Delta" 使用整数 225

& comboBox2 有:
if comboBox2 = "New" 将 0 添加到在 comboBox1 中确定的整数值
comboBox2 = "Old" 将 25 添加到在 comboBox1 中确定的整数值

将在 textBox1 中输入的用户定义整数乘以上面确定的总和值,并将该整数输出到只读文本框。

非常感谢任何帮助!

【问题讨论】:

  • 你似乎有一些很好的伪代码,是什么给你带来麻烦?
  • 帮助什么?继续编写代码...
  • 提示:您需要将字符串Convert 转换为适当的类型(在本例中为int)才能进行计算。
  • 我对 C# 很陌生,所以我想我的问题是如何将字符串“alpha”与特定的整数 170 相关联?一旦我把它记下来,我很确定我能弄清楚剩下的。

标签: c# combobox


【解决方案1】:

我会为列表中的项目使用Tuple<string, int> 或类。可能是这样的:

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();
    }
}

然后您可以将一堆CBItems 添加到您的组合框中,而不仅仅是字符串:

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));

然后在您的处理程序中,您可以将 SelectedItem 强制转换为类型 CBItem。

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

int sum = cb1Item.Value + cb2Item.Value;

您可以计算出如何将该总和乘以文本框中输入的值。

【讨论】:

    猜你喜欢
    • 2015-08-03
    • 2022-01-23
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多