C# 如何解决“InvalidCastException”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14327071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:27:57  来源:igfitidea点击:

How do I solve an "InvalidCastException"?

c#winformscasting

提问by gallie

I'm getting an "InvalidCastException" during run time on the following code:

InvalidCastException在以下代码的运行时收到“ ”:

My C# WinForm code contains a comboBox which is populated from a database with the following code:

我的 C# WinForm 代码包含一个组合框,它是从数据库中填充的,代码如下:

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

The ValueMember(CompetitionFormatId) is a list of numbers and the DisplayMember(CompetitionFormatType) is a stringof text. When I change the item in this comboBox during run time I get the error "InvalidCastException".

ValueMemberCompetitionFormatId)是号码清单和DisplayMemberCompetitionFormatType)是string文字。当我在运行时更改此组合框中的项目时,出现错误“ InvalidCastException”。

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

Any ideas what i'm doing wrong and how I can get around it?

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

采纳答案by gallie

I finally got the answer to this and it's answered on this site to another similar question. Find answer here: Stop comboBox's selectedIndexChanged event from firing when the form loads

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

The answer is: If you want to react only when the user changes the selected item in the combo box, then it is better to subscribe to SelectionChangeCommitted rather than SelectedIndex(or Value)Changed.

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

回答by psantiago

Like the exception implies, you're trying to cast a string to an int, which is invalid. Instead, you should call something like:

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

competitionFormat = int.Parse(cbCompetitionFormat.SelectedValue);

回答by codingbiz

Try this

尝试这个

competitionFormat = Convert.ToInt32(cbCompetitionFormat.SelectedValue);

Update:

更新:

The behaviour of SelectedValue in winforms is that it returns an System.Data.DataRowViewobject representing the underlying bound data. This, obviously cannot be converted to integer. You can cast this object to the type of object that was originally bound to the combobox

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

competitionFormat = ((Competition) cbCompetitionFormat.SelectedValue).CompetitionFormatId;

回答by COLD TOLD

You have to check if it is an integer.

你必须检查它是否是一个整数。

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

if (result) { }

回答by MikeTheLiar

The problem lies here:

问题出在这里:

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

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

SelectedValue仅返回 - 选定的值,而不是选定的索引。使用该属性SelectedIndex将返回您想要的内容(0 索引),并且(我认为)您甚至不需要强制转换它:

competitionFormat = cbCompetitionFormat.SelectedValue;