Reputation: 1051
I am trying to get the data from SQL Server database.
I have a table called Standard
in my database. It has three columns StandardID
, StandardName
, and Description
.
I have a combobox in which I fill the values of StandardName
Here is the code :
Using db As New SchoolDBEntities
ComboSelectStandardToEdit.DataSource = db.Standards.ToList()
ComboSelectStandardToEdit.ValueMember = "StandardID"
ComboSelectStandardToEdit.DisplayMember = "StandardName"
End Using
Now I have 2 textboxes called txtStandardName
and txtDescription
.
I want to fill the values of these 2 textboxes based on selected StandardName
from the combobox.
Here is the code I tried :
Using db As New SchoolDBEntities
Dim standard = From s In db.Standards
Where s.StandardId = CInt(ComboSelectStandardToEdit.SelectedValue)
Select s
txtStandardName.Text = CType(standard, Standard).StandardName
End Using
but unfortunately I got error :
Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery
`1[EF_WinForms_VB.Standard]' to type 'EF_WinForms_VB.Standard'.
Upvotes: 0
Views: 162
Reputation: 2145
Try using
Dim standard = (From s In db.Standards.AsEnumerable Where s.StandardId = Convert.ToInt32(ComboSelectStandardToEdit.SelectedValue) Select s) .FirstOrDefault
txtStandardName.Text = standard.StandardName
Hope it helps.
Upvotes: 1
Reputation: 22323
try using
Dim standard = (From s In db.Standards
Where s.StandardId = CInt(ComboSelectStandardToEdit.SelectedValue)
Select s)
.FirstOrDefault
txtStandardName.Text = standard.StandardName
your Linq query currently is returing a projection which could contain multiple entries. By explicitly requesting the first object of the projection, you won't need to cast your standard before accessing it's value.
Upvotes: 2