1

对于我的项目,我正在使用一个库,它有一个预定义选项列表。我希望能够从组合框中进行选择,因此我不需要每次都编辑源。

主代码:搜索玩家。级别可以设置为 Gold、Silver、Bronze 或 All。我希望能够从组合框中进行选择。当我单击按钮运行此代码时,最后会显示错误。

var searchRequest = new SearchRequest();
var searchParameters = new PlayerSearchParameters
{
    Page = 1,
    Level = comboBox1.SelectedItem == null ? Level.All : (Level)(comboBox1.SelectedItem as ComboboxItem).Value,
    //usually set like this Level - Level.Gold,
};

组合框代码:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    foreach (Level level in Enum.GetValues(typeof(Level)))
    {
        ComboboxItem item = new ComboboxItem();
        item.Text = level.ToString();
        item.Value = level;
        comboBox1.Items.Add(item);
    }
}

组合框项代码:

public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

我认为所有这些都可以工作,但它给出了一个错误,说 NullReferenchExeption 没有被用户代码处理。并且对象引用未设置为对象的实例。

我真的需要帮助才能让它工作。

非常感谢所有帮助。

谢谢,

杰克。

4

2 回答 2

1

您可以直接从枚举绑定comboBox1如下

comboBox1.DataSource  =Enum.GetNames(typeof(Level));

那么如果你需要获得选定的枚举

Level level ; 
if( Enum.TryParse<Level>(comboBox1.SelectedValue.ToString(), out level))
{ 
        var searchParameters = new PlayerSearchParameters
        {
            Page = 1,
            Level =level 
        };
}
于 2013-08-21T06:01:19.283 回答
0

运行您在此处发布的内容后 - 我收到的唯一一次NullReferenchExeption是当我单击搜索按钮时尚未选择任何内容Combobox

您需要先检查 null 。像这样...

if (comboBox1.SelectedItem != null)
{
     var searchRequest = new SearchRequest();
     var searchParameters = new PlayerSearchParameters
     {
          Page = 1,
          Level = (Level)(comboBox1.SelectedItem as ComboboxItem).Value,
          //usually set like this Level - Level.Gold,
     };
}
于 2013-08-21T06:07:01.240 回答