I have code that looks like this:
Using dbContext as IRFEntities = New IRFEntities
Dim getProspect = (From p in dbContext.IRF_Prospects _
where p.url = prospect_url _
Select p).FirstOrDefault
If getProspect.user_id Is Nothing Then
' Prepopulate the form with their information.
' These must have a value, so we need to make sure that no column is null in the database.
ddlProgram.SelectedValue = getProspect.program
txtFirst.Text = getProspect.first_name
txtLast.Text = getProspect.last_name
txtAddress.Text = getProspect.address
txtCity.Text = getProspect.city
ddlState.SelectedValue = getProspect.state
txtZip.Text = getProspect.zip
txtPhone.Text = getProspect.phone
txtEmail.Text = getProspect.email_address
txtYearEnrolling.Text = getProspect.enrolling_in
Else
' Redirect them to login.
Response.Redirect("login.aspx")
End If
End Using
I am getting the following error:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Nullable object must have a value.
On the following line of code:
txtYearEnrolling.Text = getProspect.enrolling_in
I know why I am getting the error - the value is null in the database. What I'd like to do is pull the value if it exists, but if it doesn't, I'd like it to either take a default value or just leave the field blank. What is the best way to accomplish this?
Related
really stuck on this one. The logic doesn't seem to be different from any other Linq to Entity logic I have in the rest of my application. I'm simply writing data into a table called FAQ using Linq to Entity. But I get the message BC30311: Value of Type 'faq' cannot be converted to 'FAQ'. I can't work out what value it means.
Dim objQuestion As TextBox = gvDetails.FooterRow.FindControl("txtFooterQuestion")
Dim objAnswer As TextBox = gvDetails.FooterRow.FindControl("txtFooterAnswer")
Dim objCategory As TextBox = gvDetails.FooterRow.FindControl("txtFooterCategory")
Using DBContext As New fundmatrixEntities
Dim queryFAQ = DBContext.FAQs
Dim oFAQ As New FAQ
queryFAQ.Add(oFAQ)
oFAQ.FAQId = 5
oFAQ.Question = objQuestion.Text
oFAQ.Answer = objAnswer.Text
oFAQ.Category = objCategory.Text
oFAQ.DateCreated = Date.Now
oFAQ.DateUpdated = Date.Now
Try
DBContext.SaveChanges()
BindEmployeeDetails()
lblresult.ForeColor = Drawing.Color.Green
lblresult.Text = "details inserted successfully"
Catch ex As Exception
lblresult.Text = "There was problem inserting the FAQ!"
lblresult.ForeColor = Drawing.Color.Red
End Try
End Using
I have a dropdown list on my page (ddlProgram) which is populated via a database query like so:
Using dbContext as IRFEntities = New IRFEntities
Dim getPrograms = (From p in dbContext.IRF_Program _
Order By p.name _
Select p)
ddlProgram.DataSource = getPrograms
ddlProgram.DataTextField = "name"
ddlProgram.DataValueField = "id"
ddl.Program.DataBind()
End Using
So, for example, one might have a DataTextField of "Education" and an ID of "221".
Now, I prepopulate the form with information about the individual visiting the site (if available) - including the dropdown list like so:
If getProspect IsNot Nothing Then
If getProspect.user_id Is Nothing Then
ddlProgram.SelectedValue = getProspect.Program
End If
End If
The Program property contains a number that matches the ID of a Program. So, for example, this individual might have a Program of "221" which would match the "221" of Education mentioned above.
Currently the application successfully sets the SelectedValue to "221" for the DropDownList (ddlProgram), but the SelectedItem of the DDL remains the same (e.g., if it is initially "History" with an ID of "1" after the prepopulation it is "History" with an ID of "221").
What I'm trying to make happen is that the SelectedItem is updated to item which corresponds with the SelectedValue. So, in the end, if the individual has "221" for "Education" selected when the form is prepopulated they would see Education as the selected item and the selected value would be set correctly, whereas right now the form is showing the wrong SelectedItem but has the right SelectedValue behind the scenes.
Here is a more complete idea of the code flow from the Page_Load event:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack = False Then
' If prospect is coming from unique url
Dim prospect_url As String = Page.RouteData.Values("value")
' Save prospect_url into session variable
Session("prospect_url") = prospect_url
Using dbContext As IRFEntities = New IRFEntities
' Prepopulate the programs dropdown.
Dim getPrograms = (From p In dbContext.IRF_Program _
Order By p.name _
Select p)
ddlProgram.DataSource = getPrograms
ddlProgram.DataTextField = "name"
ddlProgram.DataValueField = "id"
ddlProgram.DataBind()
End Using
Using dbContext As IRFEntities = New IRFEntities
' Prepopulate the states dropdown.
Dim getStates = (From p In dbContext.IRF_States _
Order By p.name _
Select p)
ddlState.DataSource = getStates
ddlState.DataTextField = "name"
ddlState.DataValueField = "id"
ddlState.DataBind()
End Using
Using dbContext As IRFEntities = New IRFEntities
' Grab info. about prospect based on unique url.
Dim getProspect = (From p In dbContext.IRF_Prospects _
Where p.url = prospect_url _
Select p).FirstOrDefault
' If they have a record...
If getProspect IsNot Nothing Then
If getProspect.user_id Is Nothing Then
' Prepopulate the form with their information.
' These must have a value, so we need to make sure that no column is null in the database.
ddlProgram.SelectedValue = getProspect.program
txtFirst.Text = getProspect.first_name
txtLast.Text = getProspect.last_name
txtAddress.Text = getProspect.address
txtCity.Text = getProspect.city
ddlState.SelectedValue = getProspect.state
txtZip.Text = getProspect.zip
txtPhone.Text = getProspect.phone
txtEmail.Text = getProspect.email_address
txtYearEnrolling.Text = getProspect.enrolling_in
Else
' Redirect them to login.
Response.Redirect("login.aspx")
End If
End If
End Using
End If
End Sub
What you're doing looks like it should work. If you put a breakpoint after the setting of the value and check the SelectedItem text and value, do they appear as expected or mismatched?
Use the Immediate Window to check:
ddlProgram.SelectedItem.Text
ddlProgram.SelectedItem.Value
If they appear the same then I would presume the binding code is being refired and the list is being regenerated with the first item being selected.
To check this put a break point on the binding code and see if it is fired more than once and correct the order of the methods appropriately.
ADDED:
If it works on your local environment it should work when published, if the code is the same? Looking at your code, I'd start by seperating out some of the databinding code into seperate methods rather than have everything in Page_Load, one becuase it's good practice and two because it will make debugging easier. Further than that I'm not sure what else to suggest.
I had the following code:
If Page.IsPostBack = False Then
' If prospect is coming from unique url
Dim prospect_url As String = Page.RouteData.Values("value")
' Save prospect_url into session variable
Session("prospect_url") = prospect_url
Using dbContext As IRFEntities = New IRFEntities
' Prepopulate the states dropdown.
Dim getStates = (From p In dbContext.IRF_States _
Order By p.name _
Select p)
ddlState.DataSource = getStates
ddlState.DataTextField = "name"
ddlState.DataValueField = "id"
ddlState.DataBind()
' Grab info. about prospect based on unique url.
Dim getProspect = (From p In dbContext.IRF_Prospects _
Where p.url = prospect_url _
Select p).FirstOrDefault
' If they have a record...
If getProspect IsNot Nothing Then
'If IsDBNull(getProspect.user_id) Then
If getProspect.user_id Is Nothing Then
' Prepopulate the form with their information.
' These must have a value, so we need to make sure that no column is null in the database.
txtFirst.Text = getProspect.first_name
txtLast.Text = getProspect.last_name
txtAddress.Text = getProspect.address
txtCity.Text = getProspect.city
ddlState.SelectedValue = getProspect.state
txtZip.Text = getProspect.zip
txtPhone.Text = getProspect.phone
txtEmail.Text = getProspect.email_address
txtYearEnrolling.Text = getProspect.enrolling_in
Else
' Redirect them to login.
Response.Redirect("login.aspx")
End If
End If
End Using
End If
I then added directly below ddlState.DataBind() the following:
' Prepopulate the programs dropdown.
Dim getPrograms = (From p In dbContext.IRF_Program _
Order By p.name _
Select p)
ddlProgram.DataSource = getPrograms
ddlProgram.DataTextField = "name"
ddlProgram.DataValueField = "id"
ddlState.DataBind()
Now I get the error:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection
If I comment out the inserted code, the code works. Why is this code causing a problem?
You have lost this object:
dbContext
That is the resources (including the connection operations) for this object have already been disposed of and cleaned up. You can re-create the object if you need to databind another drop down list.
Dim dbContext as IRFEntities=Nothing
Using dbContext= New IRFEntities
//perform first databind
End Using
Using dbContext = New IRFEntities
//code to perform second databind
End Using
I have the following code:
Dim getProspect = (From p In dbContext.IRF_Prospects _
Where p.url = prospect_url _
Select p).FirstOrDefault
' If they have a record...
If Not IsDBNull(getProspect) Then
If IsDBNull(getProspect.user_id) Then
' Prepopulate the form with their information.
txtFirst.Text = getProspect.first_name
Else
' Redirect them to login.
Response.Redirect("login.aspx")
End If
When I execute it, it throws an object reference not set to an instance of an object error on getProspect.user_id. Why is it doing this? Shouldn't the fact that I'm verifying it exists using IsDBNull first keep this from happening?
DBNull is not the same as Nothing, and what you have is Nothing. FirstOrDefault, as the name suggests, returns the first item or the default value, which is Nothing for reference types - never DBNull.
Dim getProspect = (From p In dbContext.IRF_Prospects _
Where p.url = prospect_url _
Select p).FirstOrDefault
' If they have a record...
If getProspect IsNot Nothing Then
If IsDBNull(getProspect.user_id) Then
' Prepopulate the form with their information.
txtFirst.Text = getProspect.first_name
Else
' Redirect them to login.
Response.Redirect("login.aspx")
End If
I have the below code in my current solution, which returns an error of 'The value '' is invalid'. The below snippet has been shortened to just show the problem area as opposed to the entire ActionResult.
Dim tComment As New hdComment
tComment.Comment = collection("wmd-input")
tComment.MadeOn = DateTime.Now
tComment.UserID = Session("LoggedInUser")
tComment.CallID = id
If Not tComment.Comment.Trim().Length = 0 Then
db.hdComments.InsertOnSubmit(tComment)
End If
db.SubmitChanges()
Return Redirect("/Calls/Details/" & id)
However, in a previous project, I have used exactly the same code, even the view is the same, but it still returns the above error.
Everything is receiving a value ok.
The only thing that's different is that it's a different project.
I'm at a bit of a loss with this one.
Anyone have any ideas?
EDIT For reference, here is the entire ActionResult.
'
' POST: /Calls/Details/5
<Authorize()> _
<AcceptVerbs(HttpVerbs.Post)> _
<ValidateInput(False)> _
Function Details(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult
Dim calls As hdCall = callRepository.GetCall(id)
ViewData("MyCallID") = calls.CallID
ViewData("UserThatLogged") = calls.UserID
ViewData("TimeLogged") = calls.loggedOn.ToLongDateString & " " & calls.loggedOn.ToLongTimeString
ViewData("Title") = calls.Title
Dim dataContext As New CustomerServiceModelDataContext
ViewData("Status") = New SelectList(dataContext.hdStatus, "StatusID", "Status", calls.StatusID)
ViewData("Type") = New SelectList(dataContext.hdCategories, "CategoryID", "Title", calls.CategoryID)
ViewData("Company") = calls.hdCompany.Company
ViewData("Priority") = New SelectList(dataContext.hdPriorities, "PriorityID", "Priority", calls.PriorityID)
ViewData("CallDetails") = calls.CallDetails
ViewData("Customer") = calls.hdCustomer.CustomerName
ViewData("CustomerID") = calls.hdCustomer.CustomerID
ViewData("CustomerCallCount") = callRepository.CountCallsForThisCustomer(calls.hdCustomer.CustomerID).Count()
ViewData("ContactNumber") = calls.hdCustomer.Telephone
ViewData("AssignedTo") = New SelectList(dataContext.aspnet_Users, "UserName", "UserName", calls.AssignedTo)
Dim callComments = callRepository.GetCallComments(id)
Dim db As New CustomerServiceModelDataContext
Try
Dim tComment As New hdComment
tComment.Comment = collection("wmd-input")
tComment.MadeOn = DateTime.Now
tComment.UserID = Session("LoggedInUser")
tComment.CallID = id
If Not tComment.Comment.Trim().Length = 0 Then
db.hdComments.InsertOnSubmit(tComment)
End If
'Update any call changes
Dim tCall = (From c In db.hdCalls _
Where c.CallID = id _
Select c).SingleOrDefault
tCall.updatedOn = DateTime.Now
tCall.UpdatedBy = Session("LoggedInUser")
tCall.StatusID = collection("Status")
tCall.AssignedTo = collection("AssignedTo")
tCall.CategoryID = collection("Type")
tCall.PriorityID = collection("Priority")
db.SubmitChanges()
Return Redirect("/Calls/Details/" & id)
Catch ex As Exception
ModelState.AddModelError("Error", ex)
Return View(callComments)
End Try
Return View(callComments)
End Function
The rest of the code works, if the wmd-input field is left blank on the form, it's only when there is something in it does it throw the error.
EDIT bit of an update to this, this line:
If Not tComment.Comment.Trim().Length = 0 Then
now reads
If (Not tComment.Comment.Trim().Length = 0) Then
and the page updates if nothing is in the wmd-input box, but if there is, it returns the The value '' is invalid.
You are probably missing a reference. Or the framework version is different.
Also is it the same development machine, is asp.net-mvc installed both places?
I managed to fix this, the problem actually lay in the Foriegn Key Contraints between hdCalls and hdComments.
I removed the contraints and recreated them and all of a sudden it was fine.