ASP Radio Button Null Value - asp-classic

I have an "edit" form that is pulling data from a specific row. Part of this form includes radio buttons (a set of four). I am able to retrieve the data from the radio button that has been selected but the other three don't have anything and I get a Null Value error. How could I prevent this? I essentially have 1 cell that pushes in the value of the radio button that was selected. In my asp code I have it set up like this:
<input <%If (CStr((rsCourseNum.Fields.Item("question1Correct").Value)) = CStr("answer1")) Then Response.Write("checked=""checked""") : Response.Write("")%> type="radio" name="question1Correct" id="question1Correct" value="answer1">
this would throw an error if answer0 was in the db since there is no answer1, I'm just not sure exactly how to set this up to prevent it from calling a null value.

What's the Response.Write("") for?
You're not getting an error because you're checking a db value that happens to be Null; you're getting an error because you're trying to convert a Null to a string. There are two* ways around this. Method one is to not do any data type conversions:
Response.Write "<input type=""radio"" name=""question1Correct"" id=""q1c"""
If rsCourseNum("question1Correct") = "answer1" Then Response.Write " checked"
Response.Write " value=""answer1""><label for=""q1c"">Question 1</label>"
This will work with Nulls because the comparison Null = "answer1" will return Null, which isn't True, so the button isn't marked.
The other method is to explicitly check for Nulls, and only do a data type conversion if the value isn't null.
Response.Write "<input type='radio' name='q" & i & "' id='q" & i & "c'"
If Not IsNull(rs("q" & i)) Then
If CStr(rs("q" & i)) = CStr(answers(i,0)) Then Response.Write " checked"
End If
Response.Write " value='" & answers(i,0) & "'>"
Response.Write "<label for='q" & i & "c'>" & answers(i,1) & "</label>"
* Well, two, uh, "proper" ways around this. There's also the hacky way: append a blank string instead of using CStr. (Thanks for the tip, Lankymart!)
If rs("q" & i) & "" = CStr(answers(i,0)) Then Response.Write " checked"

Related

How can I add/update recordset based on dynamic posted input fields? [duplicate]

on submit of a form, I would like to capture the field names and values of the forms and I want them passed without even showing in the browser (Response.Write makes them visible in the browser). How I can do this please? I am using this code:
For Each Item In Request.Form
fieldName = Item
fieldValue = Request.Form(Item)
Response.Write(""& fieldName &" = Request.Form("""& fieldName &""")")
Next
Your code is essentially correct, so just remove the Response.Write and do something else with the fieldName and fieldValue variables you're populating. After you're done with manipulating the data (either inserting it into a database or sending an e-mail), you can redirect the user to a success / thank you page.
To test that you're receiving the correct input, you can change your Response.Write to
Response.Write fieldName & " = " & fieldValue & "<br>"
Update
Here's how you could use a Dictionary Object to put your field names and field values together:
Dim Item, fieldName, fieldValue
Dim a, b, c, d
Set d = Server.CreateObject("Scripting.Dictionary")
For Each Item In Request.Form
fieldName = Item
fieldValue = Request.Form(Item)
d.Add fieldName, fieldValue
Next
' Rest of the code is for going through the Dictionary
a = d.Keys ' Field names '
b = d.Items ' Field values '
For c = 0 To d.Count - 1
Response.Write a(c) & " = " & b(c)
Response.Write "<br>"
Next
This is a very small snippet I use to show all form fields POSTED
<%
For x = 1 to Request.Form.Count
Response.Write x & ": " _
& Request.Form.Key(x) & "=" & Request.Form.Item(x) & "<BR>"
Next
%>
To complement the answer, and reply to the second question #ReneZammit asked in his comment from Jan 31, 2012 at 10:17, Creating "dynamic" ASP/VBScript variables based on the field names IS POSSIBLE!
You just have to use the "magical" Execute() function :
<%
'If the form was SUBMITTED
If (Request.Form("submitForm") = "1") then
Dim fieldName
Dim fieldValue
'Loop through all the form items
For Each Item In Request.Form
'Get Form item properties
fieldName = Item
fieldValue = Request.Form(Item)
'Use Execute() to interpret dynamically created ASP code
Execute("Dim myVar_" & fieldName)
Execute("myVar_" & fieldName & " = """ & fieldValue & """")
Next
'Use your new Dynamic variables Names, that are now REAL native variables names!
Response.Write "<br>myVar_banana = " & myVar_banana
Response.Write "<br>myVar_pear = " & myVar_pear
Response.Write "<br>myVar_tomato = " & myVar_tomato
'If the form have to be DISPLAYED
else
%>
<form method="post">
<input type="text" name="banana" value="This is Yellow">
<br>
<input type="text" name="pear" value="This may be Green">
<br>
<input type="text" name="tomato" value="This should be Red">
<input type="hidden" name="submitForm" value="1">
<input type="submit">
</form>
<%
end if
%>
More information available here : http://www.aspdev.org/asp/asp-eval-execute/

Exclude certain selections from a drop down list ASP

I'm working on a ASP (Within the payment gateway). The options in the drop down at being pulling in from a database. I can't touch the database so have to attack the matter from the code.
Here is the value name that I need to exclude _01BM(Q)
Here is the code for the drop down.
<select name="programgroup" onchange="onProgramGroup()">
<% Call buildDropDownList(strProgramGroupCode, rsProgramGroup, "ProgramGroupCode", "ProgramGroupDescription", False)%>
</select>
I would really appreciate any help on this guys.
Here is the code for the method:
Sub buildDropDownList(strCurrentSelection, objListData, strCodeName, strDescriptionName, blnIncludeOther)
If Not objListData.BOF Then
objListData.MoveFirst
End If
While Not objListData.EOF
Response.Write "<option value='" & objListData(strCodeName) & "' "
If StrComp(strCurrentSelection, objListData(strCodeName),1) = 0 then
Response.Write "selected"
End If
Response.Write ">" & objListData(strDescriptionName) & "</option>" & VbCrLf
objListData.MoveNext
Wend
if blnIncludeOther then
Response.Write "<option value='<Other>' "
If strCurrentSelection <> "" and InStr(1, "<Other>", strCurrentSelection) = 1 then
Response.Write "selected"
End If
Response.Write ">Other</option>" & VbCrLf
end if
End Sub
You will have to change the method building the drop down. Since you did not provide us with the code for it, I'll give you a skeleton, and can use it to change your actual code.
To make it more generic and less ugly, better pass the value(s) to exclude to the method, as an array, instead of hard coding them in there.
So, the method should look like this:
Sub buildDropDownList(strProgramGroupCode, rsProgramGroup, someParamHere, anotherParam, boolParam, arrValuesToExclude)
Dim excludedValuesMapping, x
Set excludedValuesMapping = Server.CreateObject("Scripting.Dictionary")
For x=0 To UBound(arrValuesToExclude)
excludedValuesMapping.Add(LCase(arrValuesToExclude(x)), True)
Next
'...unknown code here...
Do Until rsProgramGroup.EOF
strCurrentValue = rsProgramGroup(valueFieldName)
If excludedValuesMapping.Exists(LCase(strCurrentValue)) Then
'value should be excluded, you can do something here, but not write it to browser
Else
strCurrentText = rsProgramGroup(textFieldName)
Response.Write("<option value=""" & Replace(strCurrentValue, """", """) & """>" & strCurrentText & "</option>")
End If
rsProgramGroup.MoveNext
Loop
End Sub
And to use it:
<% Call buildDropDownList(strProgramGroupCode, rsProgramGroup, "ProgramGroupCode", "ProgramGroupDescription", False, Array("_01BM(Q)"))%>
Now having your code, and if you don't want to make it generic, you can also ignore specific values by having such code in the buildDropDownList sub:
Dim currentCodeValue
While Not objListData.EOF
currentCodeValue = objListData(strCodeName)
If (UCase(currentCodeValue)<>"_04GIDBM") And _
(UCase(currentCodeValue)<>"_05GIDFM") And _
(UCase(currentCodeValue)<>"_08EXHRM") And _
(UCase(currentCodeValue)<>"_10EXMKT") And _
(UCase(currentCodeValue)<>"_12EXTTH") And _
(UCase(currentCodeValue)<>"_17EXHSC") Then
Response.Write "<option value='" & currentCodeValue & "' "
If StrComp(strCurrentSelection, currentCodeValue, 1) = 0 then
Response.Write "selected"
End If
Response.Write ">" & objListData(strDescriptionName) & "</option>" & VbCrLf
End If
objListData.MoveNext
Wend
This will just skip any records with such values, and will not output a drop down option for them.

Looping through a form to get field names and filed values issue (classic ASP)

on submit of a form, I would like to capture the field names and values of the forms and I want them passed without even showing in the browser (Response.Write makes them visible in the browser). How I can do this please? I am using this code:
For Each Item In Request.Form
fieldName = Item
fieldValue = Request.Form(Item)
Response.Write(""& fieldName &" = Request.Form("""& fieldName &""")")
Next
Your code is essentially correct, so just remove the Response.Write and do something else with the fieldName and fieldValue variables you're populating. After you're done with manipulating the data (either inserting it into a database or sending an e-mail), you can redirect the user to a success / thank you page.
To test that you're receiving the correct input, you can change your Response.Write to
Response.Write fieldName & " = " & fieldValue & "<br>"
Update
Here's how you could use a Dictionary Object to put your field names and field values together:
Dim Item, fieldName, fieldValue
Dim a, b, c, d
Set d = Server.CreateObject("Scripting.Dictionary")
For Each Item In Request.Form
fieldName = Item
fieldValue = Request.Form(Item)
d.Add fieldName, fieldValue
Next
' Rest of the code is for going through the Dictionary
a = d.Keys ' Field names '
b = d.Items ' Field values '
For c = 0 To d.Count - 1
Response.Write a(c) & " = " & b(c)
Response.Write "<br>"
Next
This is a very small snippet I use to show all form fields POSTED
<%
For x = 1 to Request.Form.Count
Response.Write x & ": " _
& Request.Form.Key(x) & "=" & Request.Form.Item(x) & "<BR>"
Next
%>
To complement the answer, and reply to the second question #ReneZammit asked in his comment from Jan 31, 2012 at 10:17, Creating "dynamic" ASP/VBScript variables based on the field names IS POSSIBLE!
You just have to use the "magical" Execute() function :
<%
'If the form was SUBMITTED
If (Request.Form("submitForm") = "1") then
Dim fieldName
Dim fieldValue
'Loop through all the form items
For Each Item In Request.Form
'Get Form item properties
fieldName = Item
fieldValue = Request.Form(Item)
'Use Execute() to interpret dynamically created ASP code
Execute("Dim myVar_" & fieldName)
Execute("myVar_" & fieldName & " = """ & fieldValue & """")
Next
'Use your new Dynamic variables Names, that are now REAL native variables names!
Response.Write "<br>myVar_banana = " & myVar_banana
Response.Write "<br>myVar_pear = " & myVar_pear
Response.Write "<br>myVar_tomato = " & myVar_tomato
'If the form have to be DISPLAYED
else
%>
<form method="post">
<input type="text" name="banana" value="This is Yellow">
<br>
<input type="text" name="pear" value="This may be Green">
<br>
<input type="text" name="tomato" value="This should be Red">
<input type="hidden" name="submitForm" value="1">
<input type="submit">
</form>
<%
end if
%>
More information available here : http://www.aspdev.org/asp/asp-eval-execute/

How to Validate a textbox+dropdowns in vb for a asp.net form

Previous question which links onto this and has any addition code ref should I forget to link any, I have set it up to email me should someone submit this form and an error occur and right now should that occur for most integer or datetime fields if they fail to validate then it will show me which fields in the email failed and what was input into them.
Problem I'm having now is to validate the drop downs and the textboxs in a similar way to what I with integer and datetime fields so I can display those also in the email in case they error.
present integer and datetime validation
Catch ex As Exception
lblInformation.Text = ("<h4>Unable to save data in database</h4>" + vbNewLine + "The error was '" + ex.Message + "'" + vbNewLine + vbNewLine + vbNewLine + "The SQL Command which falied was:" + vbNewLine + "<strong>" + mySQL + "</strong>" + vbNewLine).Replace(vbNewLine, "<br />" + vbNewLine)
Dim dtb As DateTime
If Not DateTime.TryParse(DateOfBirth, dtb) Then
strEMessageBody.Append("<strong>Date Of Birth:</strong> " & DateOfBirthYear.SelectedItem.Value & "-" & DateOfBirthMonth.SelectedItem.Value & "-" & DateOfBirthDay.SelectedItem.Value & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
Dim iao As Integer
If Not Integer.TryParse(AnyOther, iao) Then
strEMessageBody.Append("<strong>Any Other:</strong> " & rblAnyOther.Text & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
then below the final validation I have the Dim for the email setting but that I sorted out in the other question.
The problem is much earlier in the page I have
Sub Upload_Click(ByVal source As Object, ByVal e As EventArgs)
If (Page.IsValid) Then
Dim Name As String
Which prevents me just using there names as shown above where I would instead call them something else but that doesn't work with strings so my main issue is having some bit of code to check if the strings are valid and for the dropdowns which would either work but always show the data in the email or would hiccup in the code,
Dim imd As Integer
If Not Integer.TryParse(dept, imd) Then
strEMessageBody.Append("<strong>Department:</strong> " & dept.Text & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
below was how it had been setup to record the department
Department = dept.SelectedItem.Value
Department = Replace(Department, "'", "''")
Summary:- Need vb code to validate if strings and dropdowns are valid and the use of try/catch block is another possible solution but I wasn't able to figure out how to implement validation for that either.
Log your values into your database. Setup a logging table called "tblLog" or something else. Record the value of ex.Message or possibly even InnerException (if it exists).
Going hand in hand with Matt's answer, there is a tool that can help you with automatically logging errors to a DB.
It's called ELMAH.
EDIT
Here are 2 validations that you might want to use:
Dim s As String = "some user input in here"
If [String].IsNullOrEmpty(s) Then
' Watch out, string is null or it is an empty string
End If
Dim cb As New ComboBox()
If cb.SelectedItem Is Nothing Then
' Watch out, combo has no item selected
End If
NOTE ComboBox is a WinForm control in this example, but the idea is the same for the ASP.NET counterpart
Since everybodies given up trying to find a solution then I'm just gona close this topic with this post as the answer.

ASP - Printing the entire request contents

I'm debugging some ASP code and I need to get a quick printout of the current Request datastructure, which I believe is an array of key/value pairs.
I see that Request.Form("key") is the method for extracting individual elements.
Any tips on printing out the entire thing?
Try this
For Each item In Request.Form
Response.Write "Key: " & item & " - Value: " & Request.Form(item) & "<BR />"
Next
Working:
For x = 1 to Request.Form.Count
Response.Write x & ": " _
& Request.Form.Key(x) & "=" & Request.Form.Item(x) & "<BR>"
Next
I have other Classic ASP code snippets here:
https://github.com/RaviRamDhali/programming-procedure/tree/master/Snippets/ASP
Try a FOR/EACH loop:
for each x in Request.Form
Response.Write(x)
Next

Resources