【问题标题】:Parsing SelectedValue of a ListBox to int using C#.NET使用 C#.NET 将 ListBox 的 SelectedValue 解析为 int
【发布时间】:2013-03-24 16:13:52
【问题描述】:

我有一个使用字典作为数据源的列表框。

当我想将列表框的 selectedvalue 解析为 int 变量时,它给了我一个强制转换异常。

字典~

Dictionary<int, string> AssetDictionary = new Dictionary<int, string>();

列表框(lstAsset)数据源~

lstAsset.DisplayMember = "Value";
//lstAssetType.ValueMember = "Key";   //This should be lstAsset as corrected in the next line
lstAsset.ValueMember = "Key";
lstAsset.DataSource = new BindingSource(AssetDictionary, null);

发生异常的那一行~

int ush = (int)lstAsset.SelectedValue; //Specified cast is not valid.

我哪里做错了?

【问题讨论】:

  • 第二行是否应该引用 lstAsset 而不是 lstAssetType?
  • 调试时lstAsset.SelectedValue的值是多少?
  • @FyodorSoikin:你是对的。我的错。我怎么能错过那个!

标签: c# .net dictionary casting listbox


【解决方案1】:

提供值成员以正确控制。

lstAsset.ValueMember = "Key";

并使用

int ush = Convert.ToInt32(lstAsset.SelectedValue.ToString());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 2011-04-21
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    相关资源
    最近更新 更多