Using Required Expression and Required Field Validators in ASP.NET - asp.net

I am having trouble validating the use inputs once the calculate button is clicked. Any help would be greatly appreciated. All text fields must be validated using the Validation Controls and should include a summary to show errors. I would like the error messages to appear in my lblMessage.Text but nothing is showing once Calculate is clicked. (SIDE NOTE: I also cannot get my Clear button to reset the textboxes to NULL. Help with that would be great too)
HTML
<body>
<form id="form1" runat="server">
<div>
<img src="images/header.jpg" alt="Get Fit" title="GetFit" width="100%"/>
</div>
<h1>Body Mass Index Calculator</h1>
<table align="center">
<tr>
<td class="auto-style4">Enter your first name:</td>
<td class="auto-style6">
<asp:TextBox ID="txtName" runat="server" TabIndex="1"></asp:TextBox>
</td>
<td class="auto-style5"> </td>
<td class="auto-style7"> </td>
</tr>
<tr>
<td class="auto-style4">Enter your age:
</td>
<td class="auto-style6">
<asp:TextBox ID="txtAge" runat="server" TabIndex="2"></asp:TextBox>
</td>
<td class="auto-style5">
</td>
<td class="auto-style7">
<asp:CompareValidator ID="cv" runat="server" ControlToValidate="txtAge" Type="Integer" Operator="DataTypeCheck" ErrorMessage="Enter a valid age" >*</asp:CompareValidator>
</td>
</tr>
<tr>
<td class="auto-style4">Enter your email:
</td>
<td class="auto-style6">
<asp:TextBox ID="txtEmail" runat="server" TabIndex="3"></asp:TextBox>
</td>
<td class="auto-style5">
</td>
<td class="auto-style7">
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ControlToValidate="txtEmail" Display="Dynamic" ErrorMessage="Enter a valid email" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="auto-style4">Enter your height:
</td>
<td class="auto-style6">
<asp:TextBox ID="txtHeight" runat="server" TabIndex="4"></asp:TextBox>
</td>
<td class="auto-style5">
<asp:Label ID="lblHeight" runat="server" Text="INCHES"></asp:Label>
</td>
<td class="auto-style7">
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtHeight" Display="Dynamic" ErrorMessage="You must enter a valid height">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style4">Enter your weight:</td>
<td class="auto-style6">
<asp:TextBox ID="txtWeight" runat="server" TabIndex="5"></asp:TextBox>
</td>
<td class="auto-style5">
<asp:Label ID="lblWeight" runat="server" Text="POUNDS"></asp:Label>
</td>
<td class="auto-style7">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtWeight" Display="Dynamic" ErrorMessage="You must enter a valid weight">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td colspan="4">
<asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label>
</td>
</tr>
</table>
<br />
<table align="center">
<tr>
<td class="auto-style2">
<asp:Button ID="btnCalculate" runat="server" Text="Calculate BMI" align="center" TabIndex="6"/>
<span style="color:darkblue;">|</span>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" align="center" TabIndex="7"/>
</td>
</tr>
</table>
<br />
<table align="center">
<tr>
<td>
<h1>Your BMI:</h1>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtBMI" runat="server" ReadOnly="True" TabIndex="8"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<h2>This means you are:
</h2>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtResults" runat="server" ReadOnly="True" TabIndex="9"></asp:TextBox>
</td>
</tr>
</table>
</form>
</body>
ASPX.VB
Partial Class _Default
Inherits System.Web.UI.Page
Public Sub ClearAll()
txtName.Text = ""
txtAge.Text = ""
txtEmail.Text = ""
txtHeight.Text = ""
txtWeight.Text = ""
End Sub
Protected Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
ClearAll()
'txtName.Text = String.Empty
'txtAge.Text = String.Empty
'txtEmail.Text = String.Empty
End Sub
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Calculate()
End Sub
Public Sub Calculate()
'Name
If txtName.Text = String.Empty Then
lblMessage.Text = "Please enter a name."
Else
End If
'Age
If txtAge.Text = String.Empty Then
lblMessage.Text = "Please enter an age."
Else
End If
'Email
If txtEmail.Text = String.Empty Then
lblMessage.Text = "Please enter an email."
Else
End If
'Height
If txtHeight.Text = String.Empty Then
lblMessage.Text = "Please enter a height."
Else
End If
'Weight
If txtWeight.Text = String.Empty Then
lblMessage.Text = "Please enter a height."
Else
End If
Dim Result As Double ' Declare "Result" as a Double.
Dim Rounded_Result As Double
Result = txtWeight.Text / (txtHeight.Text * txtHeight.Text) * 703 ' BMI Calculation.
Rounded_Result = Math.Round(Result, 1) ' Round result to 1 decimal place.
txtBMI.Text = Rounded_Result.ToString ' Display BMI using lblBMI.
BMI_Message(Rounded_Result) 'Send Rounded BMI result to Sub BMI_Message.
End Sub
Public Sub BMI_Message(ByVal BMI_Value As Double)
Select Case BMI_Value
Case 0.0 To 18.5
txtResults.Text = "Underweight"
Case 18.6 To 24.9
txtResults.Text = "Normal Weight"
Case 25.0 To 29.9
txtResults.Text = "Overweight"
Case Is >= 30.0
txtResults.Text = "Obese"
Case Else
txtResults.Text = "Unable to Determin BMI"
End Select
End Sub
End Class

Related

ASP.NET: every radiobutton returns false while it's checked

I got a problem with getting the correct value (checked true/false) of my radiobuttons inside nested repeaters.
VIEW
<table id="HoursTable">
<asp:Repeater ID="hoursRepeater" runat="server">
<HeaderTemplate>
<thead>
<tr>
<th>V</th>
<th>some text</th>
<th>some text</th>
<th>some text</th>
</tr>
</thead>
</HeaderTemplate>
<ItemTemplate>
<tr runat="server" ID="itemTemplateRow">
<td runat="server" visible="false">
<asp:HiddenField runat="server" ID="HoursIDHiddenField" Value='<%# Eval("HoursID") %>' />
</td>
<td class="centerAlign">
<input runat="server" type="radio" class="radiobuttonMain" ID="aprrovalRadioButton" Checked='<%# DataBinder.Eval(Container.DataItem, "IsApproved") %>' />
</td>
<td>some text</td>
<td>some text</td>
</tr>
<asp:Repeater runat="server" ID="temporaryHoursRepeater" OnItemDataBound="temporaryHoursRepeater_ItemDataBound">
<ItemTemplate>
<tr runat="server" ID="itemTemplateRow">
<td runat="server" visible="false">
<asp:HiddenField runat="server" ID="HoursIDHiddenField" Value='<%# Eval("HoursID") %>' />
</td>
<input runat="server" type="radio" class="radiobuttonTemp" ID="aprrovalRadioButton" Checked='<%# DataBinder.Eval(Container.DataItem, "IsApproved") %>'/>
<td>some text</td>
<td>some text</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</table>
<tr>
<td>
<asp:Button runat="server" ID="saveButton" CssClass="saveButton" Text="Save" OnClick="saveButton_Click" />
</td>
</tr>
CODE BEHIND
Protected Sub saveButton_Click(sender As Object, e As EventArgs)
For Each rptItem As RepeaterItem In urenRepeater.Items
Dim currentHoursGroup As New List(Of Hour)
currentHoursGroup.Add(DomainController.getInstance.getHour(CType(rptItem.FindControl("HoursIDHiddenField"), HiddenField).Value))
For Each rptItemC As RepeaterItem In CType(rptItem.FindControl("temporaryUrenRepeater"), Repeater).Items
currentHoursGroup.Add(DomainController.getInstance.getHour(CType(rptItemC.FindControl("HoursIDHiddenField"), HiddenField).Value))
Next
If DirectCast(rptItem.FindControl("approvalRadioButton"), HtmlInputRadioButton).Checked Then
currentHoursGroup.Remove(DomainController.getInstance.getHour(CType(rptItem.FindControl("HoursIDHiddenField"), HiddenField).Value))
DomainController.getInstance.getHour(CType(rptItem.FindControl("HoursIDHiddenField"), HiddenField).Value).deleteAllTemporaryHours()
Else
For Each rptItemT As RepeaterItem In CType(rptItem.FindControl("temporaryUrenRepeater"), Repeater).Items
If DirectCast(rptItemT.FindControl("approvalRadioButton"), HtmlInputRadioButton).Checked Then
currentHoursGroup.Remove(DomainController.getInstance.getHour(CType(rptItemT.FindControl("HoursIDHiddenField"), HiddenField).Value))
'do sth
End If
Next
End If
For Each u As Hour In currentHoursGroup
'do sth
Next
Next
End Sub
The problem is that 'DirectCast(rptItem.FindControl("approvalRadioButton"), HtmlInputRadioButton).Checked' always returns false, even it is checked.
I did hours of research, but I can't figure out what I'm doing wrong here
I found a workaround to reach what I want.
I added in each row a hiddenfield and gave it the following attribute:
Value='<%# DataBinder.Eval(Container.DataItem, "IsApproved").ToString %>'
Then I wrote some javascript to change the value (true/false) of the hiddenfield if a radiobutton was pressed.
In the code behind I check from every repeateritem the value of the hiddenfield and I got my selected rows!

asp.net repeater does not render in the browser

in the design view i can see the repeater, but in the browser the repeater is not showing at all.
created a repeater and can not render it. When we inspect the object, it does not appear. I took the code above it , called analyze registration data and repeat after the repeater and can not see , but the repeater not. What could be wrong ? Below the code from analyze registration data :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:GridView ID="GridView1" ShowHeader="false"
GridLines="None" AutoGenerateColumns="false"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table style="border: 1px solid #A55129;
background-color: #FFF7E7">
<tr>
<td style="width: 200px">
<asp:Image ID="imgEmployee"
ImageUrl='<%# Eval("PhotoPath")%>'
runat="server" />
</td>
<td style="width: 200px">
<table>
<tr>
<td>
<b>Id:</b>
</td>
<td>
<asp:Label ID="lblId"
runat="server"
Text='<%#Eval("EmployeeId") %>'>
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>Name:</b>
</td>
<td>
<asp:Label ID="lblName"
runat="server"
Text='<%#Eval("Name") %>'>
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>Gender:</b>
</td>
<td>
<asp:Label ID="lblGender"
runat="server"
Text='<%#Eval("Gender") %>'>
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>City:</b>
</td>
<td>
<asp:Label ID="lblCity"
runat="server"
Text='<%#Eval("City") %>'>
</asp:Label>
</td>
</tr>
</table>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
<td>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<table style="border: 1px solid #A55129;
background-color: #FFF7E7">
<tr>
<td style="width: 200px">
<asp:Image ID="imgEmployee"
ImageUrl='<%# Eval("PhotoPath")%>'
runat="server" />
</td>
<td style="width: 200px">
<table>
<tr>
<td>
<b>Id:</b>
</td>
<td>
<asp:Label ID="lblId"
runat="server"
Text='<%#Eval("EmployeeId") %>'>
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>Name:</b>
</td>
<td>
<asp:Label ID="lblName"
runat="server"
Text='<%#Eval("Name") %>'>
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>Gender:</b>
</td>
<td>
<asp:Label ID="lblGender"
runat="server"
Text='<%#Eval("Gender") %>'>
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>City:</b>
</td>
<td>
<asp:Label ID="lblCity"
runat="server"
Text='<%#Eval("City") %>'>
</asp:Label>
</td>
</tr>
</table>
</td>
</tr>
</table>
</ItemTemplate>
<SeparatorTemplate>
<asp:Image ID="Image1"
ImageUrl="~/Images/1x1PixelImage.png"
runat="server" />
</SeparatorTemplate>
</asp:Repeater>
</td>
</tr>
</table>
<div>
</div>
</form>
</body>
</html>
//////////////////
Imports System.Data.SqlClient
Public Class WebForm2
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim con As SqlConnection = New SqlConnection("data source=.; database=image; integrated security=SSPI")
Dim cmd As SqlCommand = New SqlCommand("Select * from tblEmployee", con)
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
GridView1.DataSource = rdr
GridView1.DataBind()
Repeater1.DataSource = rdr
Your repeater needs a datasource and then you need to call DataBind.
Repeater1.DataSource = rdr
Repeater1.DataBind()
I'd recommend that you wrap that in a Not IsPostBack conditional as well
if Not IsPostback
Repeater1.DataSource = rdr
Repeater1.DataBind()
GridView1.DataSource = rdr
GridView1.DataBind()
Repeater1.DataSource = rdr
Repeater1.DataBind()

Edit button not working on datalist causes invalid postback

I have a datalist and a binddata Sub in vb side that works on page load and I can see all my data but then when I click edit it brings up this error:-
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Here is My vb code:-
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
BindData()
End Sub
Protected Sub BindData()
Dim cn As SqlConnection = New SqlConnection()
Dim cmd As SqlCommand = New SqlCommand()
cn.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
cmd.Connection = cn
cmd.CommandText = "SELECT DISTINCT Users.User_ID, Users.FirstName, Users.LastName, Users.Password, Users.Email, Users.ContactNum, Users.Address, Users.County, Users.Gender, Users.Datejoined, Users.Dateleft, Users.Subscription_ID, Subscriptions.Subscription_type FROM Users INNER JOIN Subscriptions ON Users.Subscription_ID = Subscriptions.Subscription_ID WHERE (Users.Dateleft IS NULL)"
cn.Open()
Dim ds As SqlDataReader
ds = cmd.ExecuteReader()
MyDataList.DataSource = ds
MyDataList.DataBind()
cn.Close()
End Sub
Sub myDataList_EditCommand(sender As Object, e As DataListCommandEventArgs) Handles MyDataList.EditCommand
BindData()
MyDataList.EditItemIndex = e.Item.ItemIndex
End Sub
And this is my asp.net :-
<asp:DataList ID="MyDataList"
runat="server"
RepeatColumns="2" CellSpacing="-1" Font-Bold="False" Font-Italic="False"
Font-Names="Arial" Font-Overline="False" Font-Size="Medium"
Font-Strikeout="False" Font-Underline="False" HorizontalAlign="Center"
ShowFooter="False" ShowHeader="False"
onItemDataBound="myDataList_ItemDataBound"
onEditCommand="myDataList_EditCommand"
onCancelCommand="myDataList_CancelCommand"
onUpdateCommand="myDataList_UpdateCommand"
onDeleteCommand="myDataList_DeleteCommand"
RepeatDirection="Horizontal">
<ItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False"
Font-Strikeout="False" Font-Underline="False" HorizontalAlign="Center"
VerticalAlign="Middle" />
<ItemTemplate>
<br />
<div style="padding:15,15,15,15;font-size:10pt;font-family:Verdana">
<table class="style1">
<tr>
<td class="style2">
User ID</td>
<td>
<asp:Label ID="lblID" runat="server" Text='<%# Eval("User_ID") %>' />
</td>
</tr>
<tr>
<td class="style2">
Details</td>
<td>
<i><b>
<asp:Label ID="lblFName" runat="server" Text='<%# Eval("FirstName") %>' />
<asp:Label ID="lblLName" runat="server" Text='<%# Eval("LastName") %>' />
</i></b>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
<asp:Label ID="Address" runat="server" Text='<%# Eval("Address") %>' />
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
<asp:Label ID="lblCounty" runat="server" Text='<%# Eval("County") %>' />
</td>
</tr>
<tr>
<td class="style2">
Contact Details</td>
<td>
<asp:Label ID="lblEmail" runat="server" Text='<%# Eval("Email") %>' />
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
<asp:Label ID="lblNum" runat="server" Text='<%# Eval("ContactNum") %>' />
</td>
</tr>
<tr>
<td class="style2">
Package ID</td>
<td>
<asp:Label ID="lblSub" runat="server" Text='<%# Eval("Subscription_ID") %>' />
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
<asp:Label ID="lblDes" runat="server" Text='<%# Eval("Subscription_type") %>' />
</td>
</tr>
<tr>
<td class="align-center" colspan="2">
<asp:Button ID="btnEdit" runat="server" CommandName="Edit" Text="Edit" />
<asp:Button ID="btnDelete" runat="server" CommandName="Delete" Text="Delete" />
</td>
</tr>
</table></div>
<br />
</ItemTemplate>
<EditItemTemplate>
<table class="style1">
<tr>
<td class="style2">
User ID</td>
<td>
<asp:Label ID="lblID" runat="server" Text='<%# Eval("User_ID") %>' />
</td>
</tr>
<tr>
<td class="style2">
Details</td>
<td>
<asp:TextBox ID="txtFName" runat="server" text='<%#Container.DataItem("FirstName")%>'></asp:TextBox>
<asp:TextBox ID="txtLName" runat="server" text='<%#Container.DataItem("LastName")%>'></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style4">
<asp:TextBox ID="lblAdd" runat="server"
text='<%#Container.DataItem("Address")%>'></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
<asp:TextBox ID="lblCounty" runat="server"
text='<%#Container.DataItem("County")%>'></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
Contact Details</td>
<td>
<asp:TextBox ID="lblEmail" runat="server"
text='<%#Container.DataItem("Email")%>'></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
<asp:TextBox ID="lblNum" runat="server"
text='<%#Container.DataItem("ContactNum")%>'></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
Package ID</td>
<td>
<asp:Label ID="lblSub" runat="server" Text='<%# Eval("Subscription_ID") %>' />
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
<asp:Label ID="lblDes" runat="server" Text='<%# Eval("Subscription_type") %>' />
</td>
</tr>
<tr>
<td class="align-center" colspan="2">
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</td>
</tr>
</table>
</EditItemTemplate><SelectedItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False"
Font-Strikeout="False" Font-Underline="False" HorizontalAlign="Center"
VerticalAlign="Middle" />
I have put Page EnableEventValidation="false" but that just does nothing, i dont tell the error but nothing happens.
Please help me.
Try changing the following code:
Sub myDataList_EditCommand(sender As Object, e As DataListCommandEventArgs) Handles MyDataList.EditCommand
BindData()
MyDataList.EditItemIndex = e.Item.ItemIndex
End Sub
to this
Sub myDataList_EditCommand(sender As Object, e As DataListCommandEventArgs) Handles MyDataList.EditCommand
MyDataList.EditItemIndex = e.Item.ItemIndex
MyDataList.DataBind()
End Sub

input validation in asp.net cannot work

I'm facing a problem in validation. I have done validation checking before user submit the button. Buy why the registration still can be added into database. Previously this page worked perfectly just after combining other pages with my team mate it cannot work :(
This is my Registration.aspx :
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td width="30%" valign="top">
<table width="100%">
<tr>
<td class="TableTitle">
Member Registration
</td>
</tr>
<tr>
<td>
<p>
Please enter your account information.</p>
<asp:ValidationSummary ID="RegUserValidationSummary" runat="server" CssClass="validation"
ValidationGroup="RegUserValidationGroup" />
</td>
</tr>
<tr>
<td class="PageContent">
<div>
<fieldset>
<legend>Account Information</legend>
<table width="100%">
<tr>
<td width="35%">
<asp:Label ID="lblUserName" runat="server" AssociatedControlID="txtUserName">Username:</asp:Label>
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server" CssClass="textEntry" Width="130px"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="txtUserName"
CssClass="failureNotification" ErrorMessage="User Name is required." ToolTip="User Name is required."
ValidationGroup="RegUserValidationGroup">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblPassword" runat="server" AssociatedControlID="txtPassword">Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="txtPassword" runat="server" CssClass="passwordEntry" TextMode="Password"
Width="130px"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="txtPassword"
CssClass="failureNotification" ErrorMessage="Password is required." ToolTip="Password is required."
ValidationGroup="RegUserValidationGroup">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblConfirmPassword" runat="server" AssociatedControlID="txtConfirmPassword">Confirm Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="txtConfirmPassword" runat="server" CssClass="passwordEntry" TextMode="Password"
Width="130px"></asp:TextBox>
<asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server" ControlToValidate="txtConfirmPassword"
CssClass="failureNotification" Display="Dynamic" ErrorMessage="Confirm Password is required."
ToolTip="Confirm Password is required." ValidationGroup="RegUserValidationGroup">*</asp:RequiredFieldValidator>
<asp:CompareValidator ID="PasswordCompare" runat="server" ControlToCompare="txtPassword"
ControlToValidate="txtConfirmPassword" CssClass="failureNotification" Display="Dynamic"
ErrorMessage="The Confirm Password must match the Password entry." ValidationGroup="RegUserValidationGroup">*</asp:CompareValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblSecQuestion1" runat="server" AssociatedControlID="ddlSecQuestion">Security Question:</asp:Label>
</td>
<td>
<asp:DropDownList ID="ddlSecQuestion" runat="server" Width="250px">
<asp:ListItem>Where were you when you had your first kiss? </asp:ListItem>
<asp:ListItem>What was your dream job as a child? </asp:ListItem>
<asp:ListItem>What is the first name of the boy or girl that you first kissed?</asp:ListItem>
<asp:ListItem Value="•What is the middle name of your youngest child?">What is the middle name of your youngest child?</asp:ListItem>
<asp:ListItem>What is the name of your favourite pet?</asp:ListItem>
<asp:ListItem>In what city or town did your mother and father meet?</asp:ListItem>
<asp:ListItem>In what city or town was your first job?</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblSecAns" runat="server" AssociatedControlID="TxtSecAns">Security Answer:</asp:Label>
</td>
<td>
<asp:TextBox ID="TxtSecAns" runat="server" Width="130px"></asp:TextBox>
<asp:RequiredFieldValidator ID="SecAnsRequired" runat="server" ControlToValidate="TxtSecAns"
CssClass="failureNotification" ErrorMessage="Security Answer is required." ToolTip="Security Answer is required."
ValidationGroup="RegUserValidationGroup">*</asp:RequiredFieldValidator>
</td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Personal Information</legend>
<table width="100%">
<tr>
<td width="35%">
<asp:Label ID="lblName" runat="server" AssociatedControlID="txtName">Name:</asp:Label>
</td>
<td>
<asp:TextBox ID="txtName" runat="server" Width="130px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
CssClass="failureNotification" ErrorMessage="Name is required." ToolTip="Name is required."
ValidationGroup="RegUserValidationGroup">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblICNumber" runat="server" AssociatedControlID="txtICNumber">IC Number:</asp:Label>
</td>
<td>
<asp:TextBox ID="txtICNumber" runat="server" Width="130px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtICNumber"
CssClass="failureNotification" ErrorMessage="IC Number is required." ToolTip="IC Number is required."
ValidationGroup="RegUserValidationGroup">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtICNumber"
CssClass="failureNotification" ErrorMessage="Invalid Format of IC Number." ValidationExpression="\d{6}-\d{2}-\d{4}"
ValidationGroup="RegUserValidationGroup">*</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblEmail" runat="server" AssociatedControlID="txtEmail">Email:</asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmail" runat="server" Width="130px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtEmail"
CssClass="failureNotification" ErrorMessage="Email is required." ToolTip="Email is required."
ValidationGroup="RegUserValidationGroup">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtEmail"
CssClass="failureNotification" ErrorMessage="Invalid Format of Email." ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ValidationGroup="RegUserValidationGroup">*</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblContactNumber" runat="server" AssociatedControlID="txtContactNumber">Contact Number:</asp:Label>
</td>
<td>
<asp:TextBox ID="txtContactNumber" runat="server" Width="130px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtContactNumber"
CssClass="failureNotification" ErrorMessage="Contact Number is required." ToolTip="Contact Number is required."
ValidationGroup="RegUserValidationGroup">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblAddress" runat="server" AssociatedControlID="txtAddress">Address:</asp:Label>
</td>
<td>
<asp:TextBox ID="txtAddress" runat="server" Width="160px" Height="60px" TextMode="MultiLine"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txtAddress"
CssClass="failureNotification" ErrorMessage="Address is required." ToolTip="Address is required."
ValidationGroup="RegUserValidationGroup">*</asp:RequiredFieldValidator>
</td>
</tr>
</table>
</fieldset>
<p class="submitButton">
<asp:ImageButton ID="bthSubmit" runat="server" CommandName="Submit" ImageUrl="~/Forms/image/Button/Submit1.png"
ValidationGroup="RegUserValidationGroup" />
<asp:ImageButton ID="btnCancel" runat="server" CausesValidation="False" CommandName="Cancel"
ImageUrl="~/Forms/image/Button/cancel.png" />
</p>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</asp:Content>
Here is my Registration.aspx.vb :
Imports System.Data.Common
Partial Class Forms_Account_Registration
Inherits System.Web.UI.Page
Private memberObj As New MemberObj
Private memberManager As New MemberManager
Protected Sub bthSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles bthSubmit.Click
Dim oCommand As DbCommand = DbManager.GetCommandSP
Dim encryptor As New Encryption.Encryptor
Dim isDuplicateUser As Boolean
Dim isDuplicateIC As Boolean
Try
If memberManager.CheckDuplicateUser(oCommand, (txtUserName.Text.Trim).ToLower) = False Then
isDuplicateUser = False
Else
isDuplicateUser = True
End If
If isDuplicateUser = False Then
If memberManager.CheckDuplicateUserIC(oCommand, (txtICNumber.Text.Trim)) = False Then
isDuplicateIC = False
Else
isDuplicateIC = True
lblErrorMsg.Text = "Sorry,This IC number has been registered. An IC number can use to create ONE account only."
myDiv.Visible = True
End If
Else
isDuplicateIC = True
lblErrorMsg.Text = "Sorry, this username is already in use. Please choose other username."
myDiv.Visible = True
End If
Catch ex As Exception
Manager.LogManager.WriteLine(ex)
Response.Redirect("../500 Internal Server Error.aspx")
End Try
If isDuplicateIC = False Then
memberObj.UserName = txtUserName.Text.Trim.ToLower
memberObj.Password = encryptor.Encrypt(txtPassword.Text.Trim)
memberObj.SecurityQuestion = ddlSecQuestion.SelectedValue
memberObj.SecurityAnswer = TxtSecAns.Text
memberObj.MemberName = txtName.Text
memberObj.MemberIC = txtICNumber.Text
memberObj.MemberEmail = txtEmail.Text
memberObj.ContactNo = txtContactNumber.Text
memberObj.MemberAddress = txtAddress.Text
memberObj.MemberStatus = "UNBLOCK"
memberObj.isAllowedForum = "Y"
memberObj.CreatedDate = Today.Date
memberManager.Insert(oCommand, memberObj)
lblErrorMsg.Text = ""
myDiv.Visible = False
lblSuccessMsg.Text = "You have been successfully registered."
myDivSuccess.Visible = True
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
lblErrorMsg.Text = ""
myDiv.Visible = False
lblSuccessMsg.Text = ""
myDivSuccess.Visible = False
End If
End Sub
End Class

In asp:CreateUserWizard a DropDownList won't save to db?

In the 2nd step of the wizard, I have a dropdownlist that is populated from the db. when I go to the 3rd step RegisterUser.ActiveStepChanged event if fired. In there I save the data to the db. My textboxes are saving properly but my the vb code isn't pulling the selectedIndex/Value from the dropdown.
I tried populating the dropdown in Load, PreRender and neither of them helped. I also did if not Postback which didn't help either.
Any ideas?
Here is the code Sample:
Thanks.
Asp.net - It only includes relevant code:
<%# Page Title="Register" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeBehind="Register.aspx.vb" Inherits="Events.Register" EnableEventValidation="false" Trace="true" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" src="../Scripts/CommonScripts.js">
</script>
<style type="text/css">
.textInput {
width: 150px;
}
.dropdownField
{
width: 155px;
}
</style>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:CreateUserWizard ID="RegisterUser" runat="server" EnableViewState="False"
Height="68px" Width="70%" >
<FinishNavigationTemplate>
<table cellpadding="5px" width="100%">
<tr>
<td align="center" width="50%">
<asp:Button ID="FinishButton" runat="server" CommandName="MoveComplete"
Text="Finish" onclick="RegisterUser_ActiveStepChanged" /></td>
</tr>
</table>
</FinishNavigationTemplate>
<LayoutTemplate>
<asp:PlaceHolder ID="wizardStepPlaceholder" runat="server"></asp:PlaceHolder>
<asp:PlaceHolder ID="navigationPlaceholder" runat="server"></asp:PlaceHolder>
</LayoutTemplate>
<WizardSteps>
<asp:CreateUserWizardStep ID="RegisterUserWizardStep" runat="server">
<ContentTemplate>
<table style="font-size:100%;height:100%;width:100%;">
<tr>
<td align="center" colspan="2">
Sign Up for Your New Account</td>
</tr>
<tr>
<td align="right" style="width:40%">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
</td>
<td>
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
ControlToValidate="UserName" ErrorMessage="User Name is required."
ToolTip="User Name is required." ValidationGroup="RegisterUser">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server"
ControlToValidate="Password" ErrorMessage="Password is required."
ToolTip="Password is required." ValidationGroup="RegisterUser">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="ConfirmPasswordLabel" runat="server"
AssociatedControlID="ConfirmPassword">Confirm Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="ConfirmPassword" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server"
ControlToValidate="ConfirmPassword"
ErrorMessage="Confirm Password is required."
ToolTip="Confirm Password is required." ValidationGroup="RegisterUser">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Email">E-mail:</asp:Label>
</td>
<td>
<asp:TextBox ID="Email" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailRequired" runat="server"
ControlToValidate="Email" ErrorMessage="E-mail is required."
ToolTip="E-mail is required." ValidationGroup="RegisterUser">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="QuestionLabel" runat="server" AssociatedControlID="Question">Security Question:</asp:Label>
</td>
<td>
<asp:TextBox ID="Question" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="QuestionRequired" runat="server"
ControlToValidate="Question" ErrorMessage="Security question is required."
ToolTip="Security question is required." ValidationGroup="RegisterUser">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="AnswerLabel" runat="server" AssociatedControlID="Answer">Security Answer:</asp:Label>
</td>
<td>
<asp:TextBox ID="Answer" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="AnswerRequired" runat="server"
ControlToValidate="Answer" ErrorMessage="Security answer is required."
ToolTip="Security answer is required." ValidationGroup="RegisterUser">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:CompareValidator ID="PasswordCompare" runat="server"
ControlToCompare="Password" ControlToValidate="ConfirmPassword"
Display="Dynamic"
ErrorMessage="The Password and Confirmation Password must match."
ValidationGroup="RegisterUser"></asp:CompareValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color:Red;">
<asp:Literal ID="ErrorMessage" runat="server" EnableViewState="False"></asp:Literal>
</td>
</tr>
</table>
</ContentTemplate>
<CustomNavigationTemplate>
<table border="0" cellspacing="5" style="width:100%;height:100%;">
<tr align="right">
<td align="center" colspan="0">
<asp:Button ID="StepNextButton" runat="server" CommandName="MoveNext"
Text="Create User" ValidationGroup="RegisterUser" />
</td>
</tr>
</table>
</CustomNavigationTemplate>
</asp:CreateUserWizardStep>
<asp:WizardStep runat="server" Title="General Information" StepType="Finish"
ID="GeneralInfo">
<table style="font-size:100%; width:100%; height:100%">
<tr>
<td align="center" colspan="2">
Please Add Additional Account Information</td>
</tr>
<td align="right">
Birthday:
</td>
<td>
<asp:TextBox class="textInput" ID="Birthday" runat="server"></asp:TextBox>
<asp:ImageButton ID="BirthdayButton" runat="server" ImageUrl="~/Images/Calendar.png" Height="24" Width="24" ImageAlign="Baseline" />
<asp:CalendarExtender TargetControlID="Birthday" ID="BirthdayExtender" runat="server" PopupButtonID="BirthdayButton" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="Birthday" ErrorMessage="Birthday is required."
ToolTip="Birthday is required." ValidationGroup="RegisterUser">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
Religious Observance:
</td>
<td>
<asp:DropDownList class="dropdownField" ID="ReligiousObservance" runat="server"
DataSourceID="HashkafaDataSource" DataTextField="chvDescription"
DataValueField="intReligiousMasterID" AppendDataBoundItems="true" >
<asp:ListItem Value="0">Select One</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="HashkafaDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:EventsDB.06-ConnectionString %>"
SelectCommand="select s.chvSiteName, r.intReligiousMasterID, r.chvDescription from
tblSiteMaster as s inner join tblSiteReligious as sr on s.intSiteID=sr.intSiteID
inner join tblReligiousMaster as r on r.intReligiousMasterID=sr.intReligiousMasterID
where s.intSiteID=cast(#SiteID As int)">
<SelectParameters>
<asp:Parameter Name="SiteID"/>
</SelectParameters>
</asp:SqlDataSource>
<asp:RequiredFieldValidator ID="ReligiousObservanceRequired" runat="server"
ControlToValidate="ReligiousObservance" ErrorMessage="Religious Observance is required."
ToolTip="Religious Observance is required." ValidationGroup="RegisterUser">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color:Red;">
<asp:Literal ID="ErrorMessage" runat="server" EnableViewState="False"></asp:Literal>
</td>
</tr>
</table>
<%-- <CustomNavigationTemplate/> --%>
</asp:WizardStep>
<asp:CompleteWizardStep runat="server">
<ContentTemplate>
<table style="font-size:100%;height:68px;width:70%;">
<tr>
<td>
Your account has been successfully created.</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:Button ID="ContinueButton" runat="server" CausesValidation="False"
CommandName="Continue" Text="Continue" ValidationGroup="RegisterUser" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:CompleteWizardStep>
</WizardSteps>
<StartNavigationTemplate>
hello<br />
</StartNavigationTemplate>
<StepNavigationTemplate>
<table cellpadding="5px" width="100%">
<tr>
<td align="right"><asp:Button ID="StepPreviousButton" runat="server" CausesValidation="False"
CommandName="MovePrevious" Text="Previous" /> </td>
<td align="left"> <asp:Button ID="StepNextButton" runat="server" CommandName="MoveNext"
Text="Next" Height="20" Width="18" /> </td> </tr>
</table>
</StepNavigationTemplate>
</asp:CreateUserWizard>
</asp:Content>
VB.net code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'If (Not IsPostBack) Then
' PopulateReligiousDropdown()
'End If
'Scripts for state and country drop down
' Commented out because doing in ASP.Net
' Page.ClientScript.RegisterStartupScript(Me.GetType(), _
' "MyScript", _
' "window.onload=init();" & _
' "function init() { " & _
' "fillList(document.getElementById('MainContent_RegisterUser_dropCountry'), areas[5]);" & _
' "fillList(document.getElementById('MainContent_RegisterUser_dropState'), areas[0]);" & _
'" }", True)
PhotoUploadValidator.ValidationExpression = HelperMethods.regexPhotos.ToString()
RegisterUser.ContinueDestinationPageUrl = Request.QueryString("ReturnUrl")
' Populate ReligiousDropdown
HelperMethods.SiteID = HelperMethods.GetSiteID("Request.Url.Host")
HashkafaDataSource.SelectParameters.Item(0).DefaultValue = HelperMethods.SiteID
End Sub
Protected Sub RegisterUser_ActiveStepChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RegisterUser.ActiveStepChanged
' Have we JUST reached the Complete step?
If RegisterUser.ActiveStep.Title = "General Information" Then
'PopulateReligiousDropdown()
End If
If RegisterUser.ActiveStep.Title = "Complete" Then
Dim GeneralInfo As WizardStep = CType(RegisterUser.FindControl("GeneralInfo"), WizardStep)
' Programmatically reference the TextBox controls
Dim LastName As TextBox = CType(GeneralInfo.FindControl("LastName"), TextBox)
Dim FirstName As TextBox = CType(GeneralInfo.FindControl("FirstName"), TextBox)
Dim dropCountry As DropDownList = CType(GeneralInfo.FindControl("dropCountry"), DropDownList)
Dim dropState As DropDownList = CType(GeneralInfo.FindControl("dropState"), DropDownList)
Dim City As TextBox = CType(GeneralInfo.FindControl("City"), TextBox)
Dim ZipCode As TextBox = CType(GeneralInfo.FindControl("ZipCode"), TextBox)
Dim Address As TextBox = CType(GeneralInfo.FindControl("Address"), TextBox)
Dim Phone As TextBox = CType(GeneralInfo.FindControl("Phone"), TextBox)
Dim Birthday As TextBox = CType(GeneralInfo.FindControl("Birthday"), TextBox)
Dim ReligiousObservance As DropDownList = CType(GeneralInfo.FindControl("ReligiousObservance"), DropDownList)
' Dim PhotoUpload As TextBox = CType(GeneralInfo.FindControl("PhotoUpload"), TextBox)
' Update the UserProfiles record for this user
' Get the UserId of the just-added user
Dim newUser As MembershipUser = Membership.GetUser
Dim newUserId As Guid = CType(newUser.ProviderUserKey, Guid)
' Insert a new record into UserProfiles
Dim connectionString As String = ConfigurationManager.ConnectionStrings("EventsDB.06-ConnectionString").ConnectionString
Dim updateSql As String = "Insert into tblUsers " & _
"Values (#UserId, GETDATE(), #FirstName, #LastName, #dropCountry, #dropState, #City, #ZipCode, #Address, #Phone, #Birthday, #ReligiousObservance)"
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(updateSql, myConnection)
myCommand.Parameters.AddWithValue("#UserId", newUserId)
myCommand.Parameters.AddWithValue("#LastName", LastName.Text.Trim())
myCommand.Parameters.AddWithValue("#FirstName", FirstName.Text.Trim())
myCommand.Parameters.AddWithValue("#dropCountry", dropCountry.SelectedValue)
myCommand.Parameters.AddWithValue("#dropState", dropState.SelectedValue)
myCommand.Parameters.AddWithValue("#City", City.Text.Trim())
myCommand.Parameters.AddWithValue("#ZipCode", ZipCode.Text.Trim())
myCommand.Parameters.AddWithValue("#Address", Address.Text.Trim())
myCommand.Parameters.AddWithValue("#Phone", Phone.Text.Trim())
myCommand.Parameters.AddWithValue("#Birthday", Birthday.Text.Trim())
myCommand.Parameters.AddWithValue("#ReligiousObservance", ReligiousObservance.SelectedIndex)
'The dropdown's are not populating the server. The Value isn't being passed
' and I don't know why?!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
End If
End Sub

Resources