Asp.net get value from Textbox in aspx to code behind - c#

I'm creating a login system in asp.net and C# programming language. The code behind to handle the user and password is done. But in view layer, I'm troubling to get the values from username textbox and password textbox and passing it to codebehind.
Both textboxes are ID identified and in my few skills of programming, an ID should be enough to access the elements.
This is my aspx login page:
<asp:Login ID="Login1" runat="server" ViewStateMode="Disabled" RenderOuterTable="false">
<LayoutTemplate>
<p class="validation-summary-errors">
<asp:Literal runat="server" ID="FailureText" />
</p>
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
<asp:Label ID="Label1" runat="server" AssociatedControlID="UserName">User name</asp:Label>
<asp:TextBox runat="server" ID="UserName" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="UserName" CssClass="field-validation-error" ErrorMessage="The user name field is required." />
</li>
<li>
<asp:Label ID="Label2" runat="server" AssociatedControlID="Password">Password</asp:Label>
<asp:TextBox runat="server" ID="Password" TextMode="Password" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="Password" CssClass="field-validation-error" ErrorMessage="The password field is required." />
</li>
<li>
<asp:CheckBox runat="server" ID="RememberMe" />
<asp:Label ID="Label3" runat="server" AssociatedControlID="RememberMe" CssClass="checkbox">Remember me?</asp:Label>
</li>
</ol>
<asp:Button ID="Button1" runat="server" CommandName="Login" Text="Log in" OnClick="Button1_Click"/>
</fieldset>
</LayoutTemplate>
</asp:Login>
This I did do get values from UserName and Password Textboxes:
Using the code:
string user = this.UserName.Text;
string pass = this.Password.Text;
Using the code:
Textbox UserName = this.FindControl("UserName");
Deleted the aspx.design.cs and right click on the form and Convert it to application;
In the designer, add the following lines of code:
protected global::System.Web.UI.WebControls.TextBox UserName;
protected global::System.Web.UI.WebControls.TextBox Password;
Nothing worked so far, and when I reach this line:
string user = this.UserName.Text;
It throws me an error:
Object Reference not set an instance of an object.
Can you suggest any solution to my problem?

This is because these controls are parts of a template. They are not directly on the page, they are added there dynamically when Login control is initialized. To access them you need FindControl:
string user = ((TextBox)Login1.FindControl("UserName")).Text;

Related

CompareValidator without RequiredFieldValidator?

So I've been looking all over and can't seem to find a similar problem.
Basically, it seems like using CompareValidator doesn't work without a RequiredFieldValidator.
<div class="control-group">
<label class="control-label" for="PositionName">
Password:</label>
<div class="controls">
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
<%--<asp:RequiredFieldValidator ID="rvPassword" runat="server" ControlToValidate="txtPassword"
ErrorMessage="Please Enter Password" SetFocusOnError="True" ValidationGroup="1"
CssClass="error"></asp:RequiredFieldValidator>--%>
</div>
</div>
<div class="control-group">
<label class="control-label" for="PositionName">
Confirm Password:</label>
<div class="controls">
<asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqConPass" runat="server" ControlToValidate="txtConfirmPassword"
ErrorMessage="Please Enter Confirm Password" SetFocusOnError="True" ValidationGroup="1"
CssClass="error"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="compPassword" runat="server" ControlToValidate="txtConfirmPassword"
ControlToCompare="txtPassword" ErrorMessage="Password Mismatch" SetFocusOnError="True"
ValidationGroup="1" CssClass="error"></asp:CompareValidator>
</div>
</div>
Basically, you can see I have the RequiredFieldValidator commented out for both pass and confirm pass. When I do this, I can submit with only a value in the txtPassword textbox and nothing in the txtConfirmPassword textbox.
If I uncomment the RequiredFieldValidators then it compares as it should.
If it helps, the reason I need to do this is because I am unable to decrypt the password and autofill the textbox with their current password. So whenever a user is editted, they will need to enter a new password everytime with a RequiredFieldValidator on it.
So my solution was to get rid of the RequiredFieldValidator and just check if the text is null or empty, and if it is, don't update the password, but if it isn't then update the user without updating the password.
I hope this makes sense, and if anyone can help I would greatly appreciate it.
If you need more info please ask.
Thanks again!
See this code snippet, in this first for password i have used Regular expression validator and once password is valid then i have enabled compare validator.
<script>
function Validate() {
if (document.getElementById('<%=txtPassword.ClientID %>').value != "")
ValidatorEnable(document.getElementById('<%=ConfirmPasswordRequired.ClientID %>'), true);
else
ValidatorEnable(document.getElementById('<%=ConfirmPasswordRequired.ClientID %>'), false);
}
</script>
<p>
Password
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
<asp:RegularExpressionValidator ID="PasswordRegularExpression" runat="server"
ErrorMessage="*Password must be at least 8 characters long and include at least one Special Character, one Number, and one Capital letter."
ValidationGroup="ValidationGroup1" ValidationExpression="^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).*$"
ControlToValidate="txtPassword" >
</asp:RegularExpressionValidator>
</p>
<p>
Confirm Password:
<asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server" ControlToValidate="txtConfirmPassword"
ErrorMessage="*Confirm Password is required."
Enabled="false" ValidationGroup="ValidationGroup1"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="NewPasswordCompare" runat="server" ControlToCompare="txtPassword"
ControlToValidate="txtConfirmPassword" ErrorMessage="*Confirm Password must match with the Password."
ValidationGroup="ValidationGroup1"></asp:CompareValidator>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Save" ValidationGroup="ValidationGroup1"
OnClick="Button1_Click" OnClientClick="Validate();" />
</p>
Here's one thought, I also ended up using this solution:
How about setting the compare validator to validate the password textbox and compare it to the confirmation.
This way, the compare validator only fires if there is a value inside the password textbox.
<div class="control-group">
<label class="control-label" for="PositionName">Password:</label>
<div class="controls">
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"/>
</div>
</div>
<div class="control-group">
<label class="control-label" for="PositionName">Confirm Password:</label>
<div class="controls">
<asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password"/>
<asp:CompareValidator ID="compPassword" runat="server" ControlToValidate="txtPassword"
ControlToCompare="txtConfirmPassword" ErrorMessage="Password Mismatch" SetFocusOnError="True"
ValidationGroup="1" CssClass="error"/>
</div>
</div>

Required attribute in ASP Control

I want to know how to use required attribute in asp.net. .In html I used required attribute for mandatory fields. How to use it in asp .net?
I tried this so far, is it correct?
<p class="field-wrapper required-field">
<label>First Name</label>
<asp:TextBox ID="TextBox1" name="f_name" runat="server" required>
</asp:TextBox>
</p>
there's no required attribute. you have to use a RequiredFieldValidator
<asp:TextBox ID="TextBox1" name="f_name" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" id="reqName" controltovalidate="TextBox1" errormessage="Please enter a value!" />

Access Label.text value in a layout template

How to access and set text of an asp:label inside a layout template?
<ul class="login_panel">
<asp:Login ID="Login1" runat="server" RenderOuterTable="false" RememberMeSet="true">
<LayoutTemplate>
<asp:Panel runat="server" ID="panel1" DefaultButton="LoginButton">
<li>
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName"></asp:Label>
<asp:TextBox ID="UserName" CssClass=" txt_login" runat="server"></asp:TextBox>
</li>
</asp:Panel>
</LayoutTemplate>
</asp:Login>
</ul>
I need to set the text for label in .cs file.

ASP.NET logon and registration with browser password memory

I have followed the asp.net pages for registration and login. Everything works, except that the username/password combo is never remember by the browser (ie. browser autocomplete). This is an issue with all browsers. The key fields seem to be named appropriately, I think:
<LayoutTemplate>
<div class="formlayout">
<p>
Enter your login details</p>
<asp:ValidationSummary runat="server" DisplayMode="BulletList" CssClass="errors" />
<div class="b">
<asp:RegularExpressionValidator runat="server" Display="Dynamic" ErrorMessage="Invalid email address."
ValidationExpression="^[\w\.\-]+#[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]{1,})*(\.[a-zA-Z]{2,3}){1,2}$"
ControlToValidate="UserName" SetFocusOnError="false" >*</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator runat="server" Display="Dynamic" ErrorMessage="Enter your email address."
ControlToValidate="UserName" SetFocusOnError="false" >*</asp:RequiredFieldValidator>
Email address<div class="s">
Your login identity</div>
</div>
<div class="tb">
**<asp:TextBox runat="server" ID="UserName" />**</div>
<div class="b">
<asp:RequiredFieldValidator runat="server" Display="Dynamic"
ErrorMessage="Enter your password." ControlToValidate="UserName" SetFocusOnError="false" >*</asp:RequiredFieldValidator>
Password<div class="s">
Your registered password</div>
</div>
<div class="tb">
**<asp:TextBox runat="server" ID="Password" Name="Password" ClientIDMode="Static" TextMode="Password" />**</div>
<div class="shift">
<asp:CheckBox runat="server" ID="RememberMe" Text="Keep me logged in" />
</div>
<div class="shift">
<asp:Button ID="BtnLogin" ClientIDMode="Static" runat="server" CommandName="Login" Text="Login" />
</div>
</div>
</LayoutTemplate>
To clarify: My browser is set to remember passwords. Here's a thought... I am testing off 'localhost' -- are browsers set not to remember usernames and passwords that are running off localhost?
Your server-side code does not have anything to do with whether or not the browser's Auto-Complete works. That's a setting in the browser.

Validation Group used to validate the group not show the error message

In the form in aspx I have two textbox and one image button for each textbox.
I need validation the value for each textbox in a separate way and for this I have for each image button linked to a different event.
For this I have finded in google and I have tried this tutorial:
http://www.c-sharpcorner.com/Blogs/3625/use-of-validation-group-in-Asp-Net.aspx
But in my form the Validation Group in asp.net not working and I don't understand the reason.
What does not work are the warning messages that indicate required fields.
What's wrong?
My code aspx below, thank you in advance.
<form id="form1" runat="server">
<div>
<asp:textbox id="TextBox1" runat="server" width="100" cssclass="ddl_Class" validationgroup="First"></asp:textbox>
<asp:requiredfieldvalidator id="RequiredFieldValidator3" runat="server" controltovalidate="TextBox1"
errormessage="Error in TextBox1" text="***" display="None" validationgroup="First"></asp:requiredfieldvalidator>
<asp:regularexpressionvalidator id="RegularExpressionValidator4" runat="server" controltovalidate="TextBox1"
errormessage="TextBox1 only number" text="***" display="None" validationexpression="^\d+$" validationgroup="First"></asp:regularexpressionvalidator>
<asp:imagebutton id="btnSave1" runat="server" validationgroup="First" onclick="ButtonSave1_Click" imageurl="/Images/save_button.gif" onclientclick="if (!confirm('Confirm?')) return false;" />
<asp:textbox id="TextBox2" runat="server" width="100" cssclass="ddl_Class" validationgroup="Second"></asp:textbox>
<asp:requiredfieldvalidator id="RequiredFieldValidator4" runat="server" controltovalidate="TextBox2"
errormessage="Error " text="***" display="None" validationgroup="Second"></asp:requiredfieldvalidator>
<asp:imagebutton id="btnSave2" runat="server" validationgroup="Second" onclick="ButtonSave2_Click" imageurl="/Images/save_button.gif" onclientclick="if (!confirm('Confirm?')) return false;" />
</div>
<asp:validationsummary id="First" runat="Server" showmessagebox="true" cssclass="validation-summary-errors" />
<asp:validationsummary id="Second" runat="Server" showmessagebox="true" cssclass="validation-summary-errors" />
</form>
I have verified your code, only problem that I identified is missing validation group in validation summary tag.
See below:
<asp:validationsummary id="First" validationgroup="First" runat="Server" showmessagebox="true" cssclass="validation-summary-errors" />
<asp:validationsummary id="Second" validationgroup="Second" runat="Server" showmessagebox="true" cssclass="validation-summary-errors" />
Hope this will work

Categories