Conversion from string “” to type 'Byte' is not valid [closed] - asp.net

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have been struggling with this error for a couple days now, I have gone over the code to try to find an instance where I have the wrong type, but no luck. I am getting the "Conversion from string “” to type 'Byte' is not valid" when the submit button is clicked. So my thought is that there is something wrong in the Data_Save function. But I am unable to see my mistake. any help would be appreciated.
Protected Function Data_Save() As Boolean
Data_Save = False
Try
Dim newTable As New DemoOp_WebDataTable
Dim newRow As DemoOp_WebRow = newTable.NewRow()
newRow.DOW_FName = Me.txtFName.Text
newRow.DOW_LName = Me.txtLName.Text
newRow.DOW_Addr_1 = Me.txtAddr_1.Text
newRow.DOW_Addr_2 = Me.txtAddr_2.Text
newRow.DOW_City = Me.txtCity.Text
newRow.DOW_State = Me.ddState.SelectedValue.ToString
newRow.DOW_Zip = Me.txtZip.Text
newRow.DOW_Home_Phone = Me.txtHome_Phone.Text
newRow.DOW_Work_Phone = String.Empty
newRow.DOW_Cell_Phone = Me.txtCell_Phone.Text
newRow.DOW_Email = Me.txtEmail.Text
newRow.DOW_Dem_Exp = String.Empty
newRow.DOW_Wkd_Ret = String.Empty
newRow.DOW_Bilingual = String.Empty
newRow.DOW_Lang_Spk = String.Empty
newRow.DOW_Hrd_Store = Me.ddlOptQst12.SelectedItem.Value
newRow.DOW_StoreCode = Me.ddAd_Code.SelectedValue.ToString
newRow.DOW_In_Date = Now
newRow.DOW_18Plus = Me.rblnewqst1.SelectedValue
newRow.DOW_Transportation = Me.rblnewqst2.SelectedValue
newRow.DOW_AbleToStand = Me.rblnewqst3.SelectedValue
newRow.DOW_Internet = Me.rblnewqst4.SelectedValue
newRow.DOW_DirectDeposit = Me.rblnewqst5.SelectedValue
newRow.DOW_Experience = Me.rblnewqst6.SelectedValue
newRow.DOW_Outgoing = Me.rblnewqst7.SelectedValue
newRow.DOW_CulinarySkills = Me.rblnewqst8.SelectedValue
newRow.DOW_DemoWorkType = Me.ddlOptQst1.SelectedItem.Value
newRow.DOW_ReceiveTextMsgs = Me.rblOptQst2.SelectedValue
newRow.DOW_AgeCategory = Me.ddlOptQst3.SelectedItem.Value
newRow.DOW_ComputerSkill = Me.ddlOptQst4.SelectedItem.Value
newRow.DOW_CookingSkill = Me.ddlOptQst5.SelectedItem.Value
newRow.DOW_PhysicallyFit = Me.ddlOptQst6.SelectedItem.Value
newRow.DOW_AreasOfExp = GetCheckValues(chkOptQst7)
newRow.DOW_SpecialExpertise = GetCheckValues(chkOptQst8)
newRow.DOW_OtherLanguage = Me.ddlOptQst9.SelectedItem.Value
newRow.DOW_Felony = Me.rblnewqst11.SelectedValue
newRow.DOW_SOffender = Me.rblnewqst12.SelectedValue
newRow.DOW_ShopLift = Me.rblnewqst13.SelectedValue
newRow.DOW_FoodHandlers = Me.rblnewqst10.SelectedValue
newRow.DOW_OtherAgencies = GetCheckValues(chkOptQst10)
newRow.DOW_CookingAppliances = GetCheckValues(chkOptQst11)
newRow.DOW_Hrd_Store_Detail = Me.ddlOptQst13.SelectedItem.Value
Dim ta As DemoOp_WebTableAdapter = New DemoOp_WebTableAdapter
'ta.Insert(newRow.DOW_FName, newRow.DOW_LName, newRow.DOW_Addr_1, newRow.DOW_Addr_2, newRow.DOW_City, _
' newRow.DOW_State, newRow.DOW_Zip, newRow.DOW_Home_Phone, newRow.DOW_Work_Phone, newRow.DOW_Cell_Phone, _
' newRow.DOW_Email, newRow.DOW_Dem_Exp, newRow.DOW_Wkd_Ret, newRow.DOW_Bilingual, newRow.DOW_Lang_Spk, _
' newRow.DOW_Hrd_Store, newRow.DOW_Hrd_Store_Detail, newRow.DOW_StoreCode, newRow.DOW_18Plus, newRow.DOW_Transportation, _
' newRow.DOW_AbleToStand, newRow.DOW_Internet, newRow.DOW_DirectDeposit, newRow.DOW_Felony, newRow.DOW_SOffender, newRow.DOW_ShopLift, newRow.DOW_Experience, _
' newRow.DOW_Outgoing, newRow.DOW_CulinarySkills, newRow.DOW_FoodHandlers, newRow.DOW_DemoWorkType, newRow.DOW_ReceiveTextMsgs, _
' newRow.DOW_AgeCategory, newRow.DOW_ComputerSkill, newRow.DOW_CookingSkill, newRow.DOW_PhysicallyFit, _
' newRow.DOW_AreasOfExp, newRow.DOW_SpecialExpertise, newRow.DOW_OtherAgencies, newRow.DOW_CookingAppliances, newRow.DOW_OtherLanguage)
ta.Insert(newRow.DOW_FName, newRow.DOW_LName, newRow.DOW_Addr_1, newRow.DOW_Addr_2, newRow.DOW_City, _
newRow.DOW_State, newRow.DOW_Zip, newRow.DOW_Home_Phone, newRow.DOW_Work_Phone, newRow.DOW_Cell_Phone, _
newRow.DOW_Email, newRow.DOW_Dem_Exp, newRow.DOW_Wkd_Ret, newRow.DOW_Bilingual, newRow.DOW_Lang_Spk, _
newRow.DOW_Hrd_Store, newRow.DOW_StoreCode, newRow.DOW_18Plus, newRow.DOW_Transportation, _
newRow.DOW_AbleToStand, newRow.DOW_Internet, newRow.DOW_DirectDeposit, newRow.DOW_Experience, _
newRow.DOW_Outgoing, newRow.DOW_CulinarySkills, newRow.DOW_DemoWorkType, newRow.DOW_ReceiveTextMsgs, _
newRow.DOW_AgeCategory, newRow.DOW_ComputerSkill, newRow.DOW_CookingSkill, newRow.DOW_PhysicallyFit, _
newRow.DOW_AreasOfExp, newRow.DOW_SpecialExpertise, newRow.DOW_OtherLanguage, newRow.DOW_Felony, newRow.DOW_SOffender, newRow.DOW_ShopLift, newRow.DOW_FoodHandlers, newRow.DOW_OtherAgencies, newRow.DOW_CookingAppliances, newRow.DOW_Hrd_Store_Detail)
Data_Save = True
Catch ex As ApplicationException
Me.lblErrMessage.Text = ex.InnerException.ToString
End Try
End Function
Protected Function GetCheckValues(ByVal chklst As CheckBoxList) As String
GetCheckValues = String.Empty
Dim i As Integer
Dim sb As StringBuilder = New StringBuilder()
For i = 0 To chklst.Items.Count - 1
If chklst.Items(i).Selected Then
sb.Append(chklst.Items(i).Value & ",")
End If
Next
'remove the last comma in sb
If sb.Length > 0 Then
Dim InputValue As String
InputValue = Left(sb.ToString(), Len(sb.ToString()) - 1)
GetCheckValues = InputValue
End If
End Function
Protected Sub Reset_Controls()
btnSubmit.Visible = False
btnCancel.Visible = False
btnBack.Visible = True
txtFName.Enabled = False
txtLName.Enabled = False
txtAddr_1.Enabled = False
txtAddr_2.Enabled = False
txtCity.Enabled = False
ddState.Enabled = False
txtZip.Enabled = False
txtHome_Phone.Enabled = False
txtCell_Phone.Enabled = False
txtEmail.Enabled = False
ddlOptQst12.Enabled = False
ddlOptQst13.Enabled = False
ddStoreCode.Enabled = False
rblnewqst1.Enabled = False
rblnewqst2.Enabled = False
rblnewqst3.Enabled = False
rblnewqst4.Enabled = False
rblnewqst5.Enabled = False
rblnewqst6.Enabled = False
rblnewqst7.Enabled = False
rblnewqst8.Enabled = False
rblnewqst10.Enabled = False
rblnewqst11.Enabled = False
rblnewqst12.Enabled = False
rblnewqst13.Enabled = False
ddlOptQst1.Enabled = False
rblOptQst2.Enabled = False
ddlOptQst3.Enabled = False
ddlOptQst4.Enabled = False
ddlOptQst5.Enabled = False
ddlOptQst6.Enabled = False
chkOptQst7.Enabled = False
chkOptQst8.Enabled = False
ddlOptQst9.Enabled = False
chkOptQst10.Enabled = False
chkOptQst11.Enabled = False
End Sub
Protected Sub btnOKMsg_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If Data_Save() Then
lblErrMessage.Text = "Your information has been submitted!"
Else
lblErrMessage.Text = "Error occurred while saving your entry. Click on 'Back' to return to main page."
End If
'Reset_Controls()
ModalPopupExtender1.Hide()
End Sub
Protected Sub btnCancelMsg_Click(ByVal sender As Object, ByVal e As System.EventArgs)
lblErrMessage.Text = "Your information was previously submitted."
ModalPopupExtender1.Hide()
End Sub
End Class

Here's a couple of suggestions to get you started:
Enable "Option strict" in your project options and fix any errors you may get. This will help you identify where you're trying to set a byte value with an empty string.
Remove all the try-catch-statements with an empty catch section.
Clean up the code, and remove the sections not relevant to your question.
Tell us where the exception occurs and the exception details...

Related

Webviewpage Model returns Nothing when deployed on web server

I am creating an ASP.Net website with VB.Net as code behind and this is the error that appears from the published version on a web server (this does not appear when run directly from the code or from the published version on the IIS server):
error message screenshot
This is a snippet from the controller:
Function Index(ByVal pSurveyName As String) As ActionResult
Try
If IsNothing(pSurveyName) Then
Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
End If
Dim l_question As Object = GetQuestion()
Return View(l_question)
Catch ex As Exception
Call ExceptionHandler(ex)
Return View()
End Try
End Function
Function GetQuestion() As Object
Dim l_questionnaire = Session("ActiveQuestionnaire")
Dim l_surveySession = Session("SurveySession")
Dim l_redirectQueue = Session("RedirectQueue")
Dim l_sessionAnswers = Session("SessionAnswers")
Dim l_CurrentQuestion As CurrentItem = New CurrentItem
Dim l_Choices As List(Of Choice) = New List(Of Choice)
Dim l_TempDBQuestions = db.Questions
Dim l_TempDBChildQuestions = db.ChildQuestions
Dim l_TempDBChoices = db.Choices
Dim l_tempFiltered_Q
Dim li_questionnaireID As Integer
Dim li_questionCtr As Integer
Dim li_total_NoOfQuestion As Integer = 0
Dim li_resultCount As Integer = 0
Dim li_childQID As Integer = 0
Dim ls_prevAnswer As String = ""
Dim ls_err As String = ""
Try
li_questionnaireID = l_questionnaire.ID
li_questionCtr = l_surveySession.QuestionCtr
If Session("Back") = False Then
li_questionCtr = GetQuestionCtr(NEXT_QUESTION, l_surveySession, l_redirectQueue, l_sessionAnswers,, ls_prevAnswer)
Else
Dim l_current = Session("CurrentQuestion")
li_questionCtr = GetQuestionCtr(PREVIOUS_QUESTION, l_surveySession, l_redirectQueue, l_sessionAnswers, l_current, ls_prevAnswer)
End If
l_tempFiltered_Q = l_TempDBQuestions.Where(Function(q) q.QuestionnaireID.Equals(li_questionnaireID) And q.QuestionOrder.Equals(li_questionCtr))
li_resultCount = l_TempDBQuestions.Where(Function(q) q.QuestionnaireID.Equals(li_questionnaireID) And q.QuestionOrder.Equals(li_questionCtr)).Count
If li_resultCount = 0 Then
l_tempFiltered_Q = l_TempDBChildQuestions.Where(Function(q) q.QuestionnaireID.Equals(li_questionnaireID) And q.QuestionOrder.Equals(li_questionCtr))
Session("FrmChildQuestions") = True
Else
Session("FrmChildQuestions") = False
End If
For Each item In l_tempFiltered_Q
'item could be from Questions or ChildQuestions
If li_resultCount = 0 Then
Session("IsNextQuestionChild") = item.IsNextQuestionChild
End If
With l_CurrentQuestion
.ID = item.ID
.QuestionnaireID = item.QuestionnaireID
.QuestionOrder = item.QuestionOrder
.Description = item.Description
.AnswerType = item.AnswerType
.AllowMultipleAnswers = item.AllowMultipleAnswers
.QuestionNo = item.QuestionNo
.Required = item.Required
.TempAnswer = ls_prevAnswer
End With
Next
If l_CurrentQuestion.AnswerType = constants.MULTIPLE_CHOICE Then
'Get Choices
Dim li_questionID As Integer = l_CurrentQuestion.ID
If li_resultCount = 0 Then
l_Choices = db.Choices.SqlQuery("select * from Choices where ChildQuestionID = " & li_questionID & "").ToList
Else
l_Choices = db.Choices.SqlQuery("select * from Choices where QuestionID = " & li_questionID & "").ToList
End If
Session("Choices") = l_Choices
End If
If Session("TotalQuestions") Is Nothing Then
li_total_NoOfQuestion = db.Database.SqlQuery(Of Integer) _
("select max(a.MaxOrder) from(select max(QuestionOrder) " &
"as MaxOrder from Questions union select QuestionOrder from " &
"ChildQuestions)a").FirstOrDefault
Session("TotalQuestions") = li_total_NoOfQuestion
End If
With l_surveySession
.QuestionCtr = li_questionCtr
End With
Session("SurveySession") = l_surveySession
Session("CurrentQuestion") = l_CurrentQuestion
Session("Back") = False
Return l_CurrentQuestion
Catch ex As Exception
Call ExceptionHandler(ex)
End Try
End Function
And this is from the view:
#ModelType Survey_App.Models.CurrentItem
#Code
ViewData("Title") = "Index"
Layout = "~/Views/Shared/_Layout.vbhtml"
Dim l_choices = Session("Choices")
Dim l_activeSurvey = Session("ActiveSurvey")
Dim ls_tempAnsType As String = Model.AnswerType.ToString 'this is the line indicated in the error msg
Dim ls_temp As String = ""
Dim ls_tempAnswer() As String = Nothing
Dim li_totalQuestions As Integer = 0
li_totalQuestions = Session("TotalQuestions")
Dim ls_POSTAction As String = vbNullString
The error appears some time (maybe 10-15 seconds) after going through the home page but not always immediately. I also tried some debugging and it looks like the session variables also return nothing after that some time.

ASP.NET vb oracle database Date input error

Im using following code to input data into orcale database via asp.net web application (vb).
Public Sub SaveRaidDetails()
lblStatus.Text = ""
Dim dt2 As DataTable = CType(ViewState("dt1"), DataTable)
Dim er As Boolean = False
Dim dtRaidDate As Date
If dt2.Rows.Count > 0 Then
Try
dtRaidDate = Convert.ToDateTime(txtRaidDate.Text)
Catch ex As Exception
er = True
End Try
If er = False Then
lblDateEr.Visible = False
Dim intDisID, intMktSeq, intAgID As Integer
Dim dblFine As Double
If ddlDistributor.SelectedValue = "" Then
intDisID = 0
Else
intDisID = ddlDistributor.SelectedValue
End If
If ddlMarkets.SelectedValue = "" Then
intMktSeq = 0
Else
intMktSeq = ddlMarkets.SelectedValue
End If
If ddlAgency.SelectedValue = "" Then
intAgID = 0
Else
intAgID = ddlAgency.SelectedValue
End If
If txtFine.Text = "" Then
dblFine = 0
Else
dblFine = Convert.ToDouble((txtFine.Text))
End If
Dim intUserSeq As Integer = Convert.ToInt32(Session("UserSeq"))
Dim ret As Boolean
Dim rd1 As New RIMS_DATA.Raids
ret = rd1.AddRaid(dtRaidDate, txtCo.Text, txtCa.Text, intDisID, Convert.ToInt32(ddlRegion.SelectedValue), intAgID, intMktSeq, txtTrader.Text, txtTraderAdd.Text, dblFine, txtRemarks.Text, intUserSeq)
If ret = True Then
Dim intRaidID As Integer = rd1.ReadLastRaid()
Dim dtBatchDt As Date
For Each dr As DataRow In dt2.Rows
Try
dtBatchDt = Convert.ToDateTime(dr("BDt"))
Catch ex As Exception
dtBatchDt = Convert.ToDateTime("01/01/2000")
End Try
ret = rd1.AddRaid2(intRaidID, Convert.ToInt32(dr("BID")), Convert.ToInt32(dr("Qty")), dr("BCd"), dtBatchDt)
Next
ClearForm(1)
lblStatus.Text = "Record inserted successfully !"
lblDateEr.Visible = True
End If
End If
End If
Else
lblStatus.Text = "Please enter the raid details !"
End If
But the issue is in the Orcle database the date is saved in wrong format like this.. 20/07/0001 . But the date in the text box which i pass to variable is 2015/07/1. I use date time picker to input date to text box. how can i fix this problem.
Is this enough for answer

Update statement in asp.net encountered with logic error?

I'm developing a project where user can can edit/update their profile, but somehow I found myself in trouble when try to update the data into Access Database. The only funniest thing is, ONLY profile picture is updated/change in database, but none for password, firstname, lastname, etc. The rest still the same. I hope someone can help me in this case, thanks in advance!
The Page Load:
If Not IsPostBack Then
DropDownList1.DataBind()
End If
LinkButtonCancel.Visible = False
FileuploadProfPic.Visible = False
TextBoxCfrmPassword.Visible = False
ButtonUpdateProf.Visible = False
TextBoxImage.Visible = False
LabelUpload.Visible = False
LabelCfnPss.Visible = False
TextBoxUsername.Enabled = False
TextBoxPassword.Enabled = False
TextBoxFirstName.Enabled = False
TextBoxLastName.Enabled = False
TextBoxEmail.Enabled = False
TextBoxHPN.Enabled = False
TextBoxUsername.ReadOnly = True
TextBoxPassword.ReadOnly = True
TextBoxFirstName.ReadOnly = True
TextBoxLastName.ReadOnly = True
TextBoxEmail.ReadOnly = True
TextBoxHPN.ReadOnly = True
UserData = Me.Data()
TextBoxUsername.Text = UserData.Username
TextBoxFirstName.Text = UserData.FirstName
TextBoxLastName.Text = UserData.LastName
TextBoxHPN.Text = UserData.MobileNumber
TextBoxEmail.Text = UserData.Email
ProfilePic.ImageUrl = UserData.ProfilePic
TextBoxImage.Text = UserData.ProfilePic
TextBoxPassword.Text = UserData.Password
The Data Function to call the data from database:
Dim dvLogin As DataView = CType(AccessDataSourceProfile.Select(DataSourceSelectArguments.Empty), DataView)
dvLogin.RowFilter = "Username = '" & DropDownList1.SelectedValue & "'"
Dim Dt As New UserLogin
Dt.Username = dvLogin(0)("Username").ToString
Dt.Password = dvLogin(0)("Password").ToString
Dt.FirstName = dvLogin(0)("FirstName").ToString
Dt.LastName = dvLogin(0)("LastName").ToString
Dt.MobileNumber = dvLogin(0)("MobileNumber").ToString
Dt.Email = dvLogin(0)("Email").ToString
Dt.ProfilePic = dvLogin(0)("ProfilePic").ToString
Return Dt
The Update Button:
strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("Product.mdb") & ";Jet OLEDB:Database Password=;"
objConn.ConnectionString = strConnString
objConn.Open()
Dim savePath As String = "C:\Users\AdananLong\Documents\Visual Studio 2010\Projects\E-Commerce\E-Commerce\"
If (FileuploadProfPic.HasFile) Then
Dim files As String = FileuploadProfPic.FileName
savePath += files
FileuploadProfPic.SaveAs(savePath)
TextBoxImage.Text = files
Try
objCmd = New OleDbCommand("UPDATE Member SET [Password] = #password, FirstName = #firstname, LastName = #lastname, MobileNumber = #mobilenumber, Email = #email, ProfilePic = #profilepic WHERE Username = #username", objConn)
objCmd.Parameters.AddWithValue("#password", TextBoxPassword.Text)
objCmd.Parameters.AddWithValue("#firstname", TextBoxFirstName.Text)
objCmd.Parameters.AddWithValue("#lastname", TextBoxLastName.Text)
objCmd.Parameters.AddWithValue("#mobilenumber", TextBoxHPN.Text)
objCmd.Parameters.AddWithValue("#email", TextBoxEmail.Text)
objCmd.Parameters.AddWithValue("#profilepic", TextBoxImage.Text)
objCmd.Parameters.AddWithValue("#username", TextBoxUsername.Text)
objCmd.ExecuteNonQuery()
DropDownList1.DataBind()
Me.LabelWarning.Visible = True
Me.LabelWarning.Text = "Update Sucessful."
Catch ex As Exception
Me.LabelWarning.Visible = True
Me.LabelWarning.Text = "Cannot Update : Error (" & ex.Message & ")"
End Try
Else
Try
objCmd = New OleDbCommand("UPDATE Member SET [Password] = #password, FirstName = #firstname, LastName = #lastname, MobileNumber = #mobilenumber, Email = #email, ProfilePic = #profilepic WHERE Username = #username", objConn)
objCmd.Parameters.AddWithValue("#password", TextBoxPassword.Text)
objCmd.Parameters.AddWithValue("#firstname", TextBoxFirstName.Text)
objCmd.Parameters.AddWithValue("#lastname", TextBoxLastName.Text)
objCmd.Parameters.AddWithValue("#mobilenumber", TextBoxHPN.Text)
objCmd.Parameters.AddWithValue("#email", TextBoxEmail.Text)
objCmd.Parameters.AddWithValue("#profilepic", TextBoxImage.Text)
objCmd.Parameters.AddWithValue("#username", TextBoxUsername.Text)
objCmd.ExecuteNonQuery()
DropDownList1.DataBind()
Me.LabelWarning.Visible = True
Me.LabelWarning.Text = "Update Sucessful."
Catch ex As Exception
Me.LabelWarning.Visible = True
Me.LabelWarning.Text = "Cannot Update : Error (" & ex.Message & ")"
End Try
End If
objConn.Close()
objConn = Nothing
This seems to be a well know effect of forgetting to test for postbacks in the Page_Load code.
Every time your user triggers an event to be handled on the server (runat="server" and/or AutoPostBack="true" ) then the Page.Load event of your page is called BEFORE calling the event handler activated by the user action. See ASP.NET Life Cycle
This means that in your Page.Load code you should be careful to not reload the page controls with values from the database otherwise, when the event handler is started, you have the controls filled with the original values extracted in the Page.Load event.
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
.....
' code to load the controls with values from database
UserData = Me.Data()
TextBoxUsername.Text = UserData.Username
TextBoxFirstName.Text = UserData.FirstName
TextBoxLastName.Text = UserData.LastName
TextBoxHPN.Text = UserData.MobileNumber
TextBoxEmail.Text = UserData.Email
ProfilePic.ImageUrl = UserData.ProfilePic
TextBoxImage.Text = UserData.ProfilePic
TextBoxPassword.Text = UserData.Password
End If
End Sub

Trying to make a group of fields required on combobox selection in Access 2010

In Access 2010.
I have 3 separate groups of fields that can be active based on a combobox selection but I'm trying to get them to be required as well. I've looked everywhere but it doesn't appear to be any VB code to make a field required. Is there anyway I can accomplish this?
The code I have right now to make the selected group of fields active and make the one's not selected blank:
Private Sub Combo109_Click()
If Combo109 = "Germ" Then
cg_moisture.Enabled = True
cg_oil_nir.Enabled = True
extraneous_material.Enabled = True
fines.Enabled = True
cg_moisture.Enabled = True
cg_oil_nir.Enabled = True
extraneous_material.Enabled = True
fines.Enabled = True
Moist_cgm_nir.Enabled = False
prot_cgm_nir.Enabled = False
oil_cgm_nir.Enabled = False
meal_color.Enabled = False
load_out_temp.Enabled = False
moist_cgf_nir.Enabled = False
prot_cgf_nir.Enabled = False
oil_cgf_nir.Enabled = False
profat_nir.Enabled = False
starch_nir.Enabled = False
total_sug_nir.Enabled = False
loadout_temp.Enabled = False
screen_thrus.Enabled = False
screen_thrus.Value = ""
Moist_cgm_nir.Value = ""
prot_cgm_nir.Value = ""
oil_cgm_nir.Value = ""
meal_color.Value = ""
load_out_temp.Value = ""
moist_cgf_nir.Value = ""
prot_cgf_nir.Value = ""
oil_cgf_nir.Value = ""
profat_nir.Value = ""
starch_nir.Value = ""
total_sug_nir.Value = ""
loadout_temp.Value = ""
screen_thrus.Value = ""
screen_thrus.Value = ""
End If
IF all of the controls are in the 'Detail' section of your form, AND if a contrtol is Enabled, you require a value, then the code below should work. If you want more meaningful names to be displayed, either change your control names, or place a better name in the control 'Tag' field and reference that. The following code only checks Textboxes and CheckBoxes - modify to suit your needs.
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim ctl As Control
Dim blnMissing As Boolean
Dim strMissing As String
For Each ctl In Me.Section("Detail").Controls
If ctl.ControlType = acTextBox Or ctl.ControlType = acCheckBox Then
If ctl.Enabled = True Then
'Debug.Print ctl.Name & vbTab & ctl.Value
If ctl.Properties("Enabled") = True Then
If Me(ctl.Name) = "" Or IsNull(Me(ctl.Name)) Then
blnMissing = True
strMissing = strMissing & ctl.Name & "; "
End If
End If
End If
End If
Next ctl
If blnMissing = True Then
MsgBox "You are required to enter data in fields: " & strMissing, vbOKOnly + vbCritical, "Missing Required Data"
Cancel = True
End If
End Sub

Session disappears unexpectedly

The site is a buy/sell site and the page the code comes from is the "add product" page.
The problem is that the session("change") becomes nothing by some reason, I can't find any errors. The payment.aspx have a button that sends me back to the page with a session("change").
The reason I see the problem is that when I try to edit something the category gets restetted to the first in the list. and when I debug I see that the session is nothing, though it should be something
Heres the code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSubmit.Click
If Not stats > 0 Then
If Session("change") IsNot Nothing Then
Dim dc As New DataClassesDataContext
Dim getP = From prod In dc.Products _
Where prod.ProductID = CInt(Session("change")) _
Select prod
If getP.Any Then
If rdbSell.Checked = True Then
getP.FirstOrDefault.BuySell = True
Else
getP.FirstOrDefault.BuySell = False
End If
If ddlSubSubcat.SelectedValue IsNot String.Empty Then
getP.FirstOrDefault.CategoryID = CInt(ddlSubSubcat.SelectedValue)
Else
getP.FirstOrDefault.CategoryID = CInt(ddlSubCat.SelectedValue)
End If
getP.FirstOrDefault.Content = txtContent.Text.Replace(Environment.NewLine, "<br />")
getP.FirstOrDefault.CountyID = CInt(ddlCounty.SelectedValue)
getP.FirstOrDefault.E_mail = txtEmail.Text
getP.FirstOrDefault.Date = DateTime.Now
getP.FirstOrDefault.Active = 0
getP.FirstOrDefault.Alias = txtAlias.Text.Replace("'", "''")
getP.FirstOrDefault.ShowEmail = 0
Dim PreID As Integer = getP.FirstOrDefault.ProductID
If chkShowEmail.Checked = True Then
getP.FirstOrDefault.ShowEmail = 1
Else
getP.FirstOrDefault.ShowEmail = 0
End If
If chkShowPhone.Checked = True Then
getP.FirstOrDefault.ShowPhone = 1
Else
getP.FirstOrDefault.ShowPhone = 0
End If
getP.FirstOrDefault.Headline = txtHeadline.Text
getP.FirstOrDefault.Password = txtPassword.Text
getP.FirstOrDefault.Phone = txtPhone.Text
getP.FirstOrDefault.Price = txtPrice.Text
If chkUnknown.Checked = True Then
getP.FirstOrDefault.YearModel = String.Empty
Else
getP.FirstOrDefault.YearModel = ddlYear.SelectedValue
End If
For Each item In libPictures.Items
Dim i As String = item.ToString
Dim imagecheck = From img In dc.Pictures _
Where img.Name = i And img.ProductID = CInt(Session("change")) _
Select img
If imagecheck.Any Then
Else
Dim img As New Picture
img.Name = item.ToString
img.ProductID = CInt(Session("change"))
dc.Pictures.InsertOnSubmit(img)
dc.SubmitChanges()
End If
Next
dc.SubmitChanges()
Session.Remove("change")
Response.Redirect("~/precheck.aspx?id=" + PreID.ToString)
End If
Else
Dim dc As New DataClassesDataContext
Dim prod As New Product
If rdbSell.Checked = True Then
prod.BuySell = True
Else
prod.BuySell = False
End If
If ddlSubSubcat.DataValueField IsNot String.Empty Then
prod.CategoryID = CInt(ddlSubSubcat.SelectedValue)
Else
prod.CategoryID = CInt(ddlSubCat.SelectedValue)
End If
prod.Content = txtContent.Text.Replace(Environment.NewLine, "<br />")
prod.CountyID = CInt(ddlCounty.SelectedValue)
prod.E_mail = txtEmail.Text
prod.Date = DateTime.Now
prod.Active = 0
prod.Alias = txtAlias.Text.Replace("'", "''")
prod.ShowEmail = 0
If chkShowEmail.Checked = True Then
prod.ShowEmail = 1
Else
prod.ShowEmail = 0
End If
If chkShowPhone.Checked = True Then
prod.ShowPhone = 1
Else
prod.ShowPhone = 0
End If
prod.Headline = txtHeadline.Text
prod.Password = txtPassword.Text
prod.Phone = txtPhone.Text
prod.Price = txtPrice.Text
If chkUnknown.Checked = True Then
prod.YearModel = String.Empty
Else
prod.YearModel = ddlYear.SelectedValue
End If
dc.Products.InsertOnSubmit(prod)
dc.SubmitChanges()
Dim PreID As Integer = prod.ProductID
For Each item In libPictures.Items
Dim img As New Picture
img.Name = item.ToString
img.ProductID = prod.ProductID
dc.Pictures.InsertOnSubmit(img)
dc.SubmitChanges()
Next
Session.Remove("change")
Response.Redirect("./precheck.aspx?id=" + PreID.ToString, False)
End If
End If
stats = 0
'Catch ex As Exception
'End Try
End Sub
It depends upon how the application is managing session state. If your session state is managed InProc then if the application pool is recycled then all your session information will be lost. If that is happening then it could be a good option to store session state in SQL Server which will persist between app pool recycling.
More info:
ASP.NET Session State Overview
ASP.NET State Management Recommendations

Resources