0

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'.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

T get this error at runtime : Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.
seems this may be related to your where clause, at one point you are using StandardID and in the other you are using StandardId which isn't a property on the object
@user2524507: You probaby have to extract the CInt conversion out of the query before the Dim standard ... line: Dim standardId = CInt(ComboSelectStandardToEdit.SelectedValue) and then the Where clause: Where s.StandardId = standardId
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.