简体   繁体   English

C# Visual Studio2019 中的 System.InvalidCastException

[英]System.InvalidCastException in C# Visual Studio2019

I was trying to get IDs of combobox items in order to store them in the code and use them to replace labels whenever combobox selected items are changed.我试图获取 combobox 项目的 ID,以便将它们存储在代码中,并在 combobox 选定项目发生更改时使用它们替换标签。 However, i encountered this error.但是,我遇到了这个错误。 I used the first var testID to get the IDs of cbx items.我使用第一个 var testID 来获取 cbx 项目的 ID。 then inserted it into my getbyid method and converted it into INT.然后将其插入我的 getbyid 方法并将其转换为 INT。 IT is actually an object.它实际上是一个 object。 So when I debugged it, it crashed.所以当我调试它时,它崩溃了。 So is there any way to solve this problem?那么有没有办法解决这个问题呢?

var testID = cbxTakeTest.SelectedValue;
var Test = new TestManager().GetById(Convert.ToInt32(testID));

               lblTakeTestQuestion1.Text = Test.Q1;
               lblTakeTestQuestion2.Text = Test.Q2;
               lblTakeTestQuestion3.Text = Test.Q3;

Value member was chosen as ID in the table where test names are stored值成员被选为存储测试名称的表中的 ID

Your question was already answered here: Get ID of item selected in ComboBox您的问题已在此处得到解答: Get ID of item selected in ComboBox

In short just apply ToString() to your testID.简而言之,只需将 ToString() 应用于您的 testID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM