【问题标题】:Combobox value (binded with an enum) in an instance实例中的组合框值(与枚举绑定)
【发布时间】:2015-06-02 20:14:42
【问题描述】:

小伙子们好!

我有一个问题。

如果您看到我的表单,我想我会节省大量文字,所以我们开始吧!

表格:

private void Form1_Load(object sender, EventArgs e)
{
    /*
    Held h1 = new Held("Tank", Lanes.Top);
    Held h2 = new Held("ADC", Lanes.Bot);
    Held h3 = new Held("Support", Lanes.Bot);
    listBox1.Items.Add(h1);
    listBox1.Items.Add(h2);
    listBox1.Items.Add(h3);
    */

    //Data koppelen
    cbRol.DataSource = Enum.GetValues(typeof(Lanes));
}

private void btnAanmaken_Click(object sender, EventArgs e)
{
    int getal;

    if (CheckEmptyFields())
    {
        MessageBox.Show("Vul alle velden in!");
    }
    else
    {
        if (CheckMovementSpeedIsInt(out getal))
        {
            string naamHero = tbNaamHero.Text;
            Lanes lane = ???
            int mSpeedHero = getal;
            Held nieuwHeld = new Held(naamHero, lane, getal);
        }
    }
}

private bool CheckMovementSpeedIsInt(out int getal)
{
    return Int32.TryParse(tbMoveSpeed.Text, out getal);
}

private bool CheckEmptyFields()
{
    return tbNaamHero.Text == null || tbMoveSpeed.Text == null || cbRol.SelectedItem == null;
}

举行:

class Held
{
    private string Naam;
    private Lanes Lane;
    int MSpeed;

    public Held(string aNaam, Lanes aLane, int aMSpeed)
    {
        this.Naam = aNaam;
        this.Lane = aLane;
        this.MSpeed = aMSpeed;
    }

    public override string ToString() 
    {
        return this.Naam + " " + this.Lane.ToString();
    }

}

}

车道:

enum Lanes
{
    Top,
    Mid,
    Bot,
    Jungle
}

好的!如您所见,我已将枚举与 ComboBox 结合在一起。我想将所选值(当用户按下“Aanmaken/Create”按钮时)放入实例中。

如何将对象(从 ComboBox)转换为类型(通道)?

如果我说得不够清楚,请提醒我!

PS:“???”在代码中是我不知道该放什么的地方,因为这是问题,呵呵。

【问题讨论】:

  • @ryanyuyu 你是对的,修复它!

标签: c# combobox enums


【解决方案1】:

只需使用以下内容:

Lanes lane = (Lanes)cbRol.SelectedIndex;

这是因为 enum 是 typeof int,所以你的 Top 实际上是 0,等等...

【讨论】:

  • 非常感谢,伙计!做到了!
  • 没问题,这就是假设SO 是为:D
【解决方案2】:

你可以解析你的Enum.Parse

Lanes lange = (Lanes) Enum.Parse(typeof(Lanes), cbRol.SelectedItem.ToString(), true);

这也适用于索引

Lanes lange = (Lanes) Enum.Parse(typeof(Lanes), cbRol.SelectedIndex.ToString(), true);

【讨论】:

    猜你喜欢
    • 2012-08-19
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2018-11-12
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多