2015-07-18 141 views
0

我正试图在列表框的单击事件上填充数据列表框到文本框,但我发现这个错误无法投射'<> f__AnonymousType0`2 [System.String,System.Int32]'类型的对象来键入'System.IConvertible'

其他信息:无法转换类型的对象 '<> f__AnonymousType0`2 [System.String,System.Int32]' 为类型 'System.IConvertible'

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    StudenRecordDataContext std = new StudentRecordDataContext(); 
    int selectedValue = Convert.ToInt32(listBox1.SelectedValue); 
    StudentRecord sr = std.StudentRecords.Single(s =>s.ID==selectedValue); 
    txtId.Text = sr.ID.ToString(); 
    txtName.Text = sr.Name; 
    txtPassword.Text = sr.Password; 
    txtCnic.Text = sr.CNIC; 
    txtEmail.Text = sr.Email; 
} 

我认为错误是在线StudentRecord sr = std.StudentRecords.Single(s =>s.ID==selectedValue);

该错误来自哪里,我需要改变以解决该错误?

+0

没有工作兄弟和ID的类型int –

+0

那么你在哪里得到这个错误? –

+0

从第三行当我使用lambda exp –

回答

1

我很遗憾地这样说,但是您向我们提供了您的程序失败的错误诊断。

罪魁祸首是这一行:

int selectedValue = Convert.ToInt32(listBox1.SelectedValue); 

我希望你刚才填充的listbox1有收集从StudentRecordsStudentRecordDataContext的实例来。

如果您从列表框中选择一个值,SelectedValue将保存添加到项目集合中的对象(或通过设置DataSource属性间接)。

要修复您的代码,您可以先确保对象再次变为StudentRecord。这并不容易,因为你创建了一个匿名类型,我希望是这样的:

listbox1.DataSource = new StudentRecordDataContext() 
    .StudentRecords 
    .Select(sr => new { Name = sr.Name, ID = sr.ID }); 

当您尝试检索您得到的SelectedValue匿名类型,不是东西,是强类型。

不是增加一个匿名类型,创建一个有名称的属性和ID的新类:

class StudentRecordItem 
{ 
    public string Name {get; set;} 
    public int ID {get; set;} 
} 

当你填入数据源的每个记录创建StudentRecordItem类,添加那些数据源。

listbox1.DataSource = new StudentRecordDataContext() 
    .StudentRecords 
    .Select(sr => new StudentRecordItem { Name = sr.Name, ID = sr.ID }); 

的代码可以成为这样的事情:

StudentRecordItem selectedStudent = listBox1.SelectedValue as StudentRecordItem; 
if (selectedStudent == null) 
{ 
    MessageBox.Show("No student record"); 
    return; 
} 

int selectedValue = selectedStudent.ID; 

你不需要Convert.ToInt32因为我认为ID已经是一个int。

请记住,debugger in Visual Studio显示所有属性和变量的实际类型和值。当类型转换失败时,您可以在那里检查您正在使用的实际类型。

相关问题