2015-07-18 142 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顯示所有屬性和變量的實際類型和值。當類型轉換失敗時,您可以在那裏檢查您正在使用的實際類型。

相關問題