3

InvalidCastException在以下代码的运行时得到一个“”:

我的 C# WinForm 代码包含一个使用以下代码从数据库填充的组合框:

public void PopulateCompetitionFormatDd()
{
     var _competitionFormat            = new CompetitionFormatBL();
     cbCompetitionFormat.DataSource    = _competitionFormat.GetByAllCompetitionFormats();
     cbCompetitionFormat.ValueMember   = "CompetitionFormatId";
     cbCompetitionFormat.DisplayMember = "CompetitionFormatType";
}

( ) 是数字列表,( ValueMember)是文本。当我在运行时更改此组合框中的项目时,我收到错误“ ”。CompetitionFormatIdDisplayMemberCompetitionFormatTypestringInvalidCastException

private void cbCompetitionFormat_SelectedIndexChanged(object sender, EventArgs e)
{
     int competitionFormat = 1;
     competitionFormat = (int)cbCompetitionFormat.SelectedValue;
}

任何想法我做错了什么以及如何解决它?

4

5 回答 5

2

您必须检查它是否为整数。

int competitionFormat;
bool result = Int32.TryParse(cbCompetitionFormat.SelectedValue, out competitionFormat);

if (result) { }
于 2013-01-14T21:36:41.840 回答
1

我终于得到了这个问题的答案,并且在这个网站上回答了另一个类似的问题。在此处找到答案:表单加载时停止触发组合框的 selectedIndexChanged 事件

答案是:如果您只想在用户更改组合框中的选定项时做出反应,那么最好订阅 SelectionChangeCommitted 而不是 SelectedIndex(或 Value)Changed。

于 2013-01-21T23:25:42.950 回答
1

The problem lies here:

private void cbCompetitionFormat_SelectedIndexChanged(object sender, EventArgs e)
{
    int competitionFormat = 1;
    competitionFormat = (int)cbCompetitionFormat.SelectedValue; // <- This is an invalid cast
}

SelectedValue returns just that - the selected value, NOT the selected index. Using the property SelectedIndex will return what you want (0 indexed), and (I think) you don't even need to cast it:

competitionFormat = cbCompetitionFormat.SelectedValue;
于 2013-01-15T00:07:37.550 回答
1

就像异常暗示的那样,您试图将字符串转换为无效的 int。相反,您应该调用类似:

competitionFormat = int.Parse(cbCompetitionFormat.SelectedValue);
于 2013-01-14T21:34:14.837 回答
0

尝试这个

competitionFormat = Convert.ToInt32(cbCompetitionFormat.SelectedValue);

更新:

Winforms 中 SelectedValue 的行为是它返回一个System.Data.DataRowView表示底层绑定数据的对象。这显然不能转换为整数。您可以将此对象转换为最初绑定到组合框的对象类型

competitionFormat = ((Competition) cbCompetitionFormat.SelectedValue).CompetitionFormatId;
于 2013-01-14T21:34:45.817 回答