尝试获取并使用分配给组合框中字符串的值

时间:2014-02-21 14:36:13

标签: c# combobox

我已经在组合框中为字符串赋值,但是我似乎无法获取变量来获取值。

示例:

this.selectquest.Items.AddRange(new Level[] {
  new Level() {Name = "Level 41", Value = 1476088},
  new Level() {Name = "Level 52", Value = 6000000},
  new Level() {Name = "Level 53", Value = 7000000}});

我想取值(基于组合框选择)并将其设置为变量:

int Value = ptexp;

然后我想用这样做数学:

int ttlvl = ptexp / tlvl;

然而,当我这样做时,它只给我数字0.如果我做反向然后它给出一个错误,说它试图除以0。

其他信息:

这是有用的:

private void calculate_Click(object sender, EventArgs e)
{
    op = "X";
    clvl = int.Parse(currentlevel.Text);
    currentlevel.Text = "";

    cexp = int.Parse(currentexp.Text);
    currentexp.Text = "";

    mexp = int.Parse(mobsexp.Text);
    mobsexp.Text = "";

    if (op == "X") 
        tlvl = clvl - cexp;
    int ttlvl = tlvl / ptexp;
    turnstolvl.Text = ttlvl.ToString();

}

private void selectquest_SelectedIndexChanged(object sender, EventArgs e)
{
    selectquest.DisplayMember = "Name";
    var v = selectquest.SelectedItem as Level;
    int Value = (selectquest.SelectedItem as Level).Value;
    ptexp = Value;
}

1 个答案:

答案 0 :(得分:0)

投射组合框的选定值以获得它:

var selectedValue = (Level)selectquest.SelectedItem;
int value = selectedValue.Value;

您可以对此事件执行此操作:comboBox1_SelectedIndexChanged

更新:

如果您希望值等于选择,请执行以下操作:

int value = (selectquest.SelectedItem as Level).Value; 
ptexp = value;