I`m trying to make an ASP.NET basic site that connects to a database. It's supposed to allow a user to register and log in.
I check the input with javascript and in the code behind in case it's disabled.
The problem is that whenever i click the register, login, or logout buttons for the first time they won't work; The page remains the same.
The second time, however, they work perfectly.
Debugger says it's called both times.
any ideas?
ASP:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Main.aspx.cs"
Inherits="Register_and_Login.Main" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script type="text/javascript">
function isUserValid() {
var UserLength = document.getElementById("UserTB").value.length;
var ValidatorLabel = document.getElementById("ValidateUser");
if (UserLength < 6 || UserLength > 15) {
ValidatorLabel.style.display = 'inline';
return false;
}
else {
ValidatorLabel.style.display = 'none';
return true;
}
}
function isPassValid() {
var PassLength = document.getElementById("PasswordTB").value.length;
var ValidatorLabel = document.getElementById("ValidatePassword");
if (PassLength < 6 || PassLength > 15) {
ValidatorLabel.style.display = 'inline';
return false;
}
else {
ValidatorLabel.style.display = 'none';
return true;
}
}
function isConfirmValid() {
var Password = document.getElementById("PasswordTB").value;
var Me = document.getElementById("ConfirmTB").value;
var ValidatorLabel = document.getElementById("ValidateConfirm");
if (Password == Me) {
ValidatorLabel.style.display = 'none';
return true;
}
else {
ValidatorLabel.style.display = 'inline';
return false;
}
}
function isEmailValid() {
var str = document.getElementById("EmailTB").value;
var lastAtPos = str.lastIndexOf('#');
var lastDotPos = str.lastIndexOf('.');
var isFine = (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('##') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
var ValidationLabel=document.getElementById("ValidateEmail");
if(isFine)
{
ValidationLabel.style.display='none';
return true;
}
else
{
ValidationLabel.style.display='inline';
return false;
}
}
</script>
<title></title>
<style type="text/css">
.Validators
{
display:none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel id="RegisterRelated" runat="server">
Username:<br />
<asp:TextBox ID="UserTB" runat="server" OnChange="isUserValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidateUser" runat="server" ForeColor="Red"
Text="Username must be 6-15 characters in length, and contain no special characters." CssClass="Validators"></asp:Label>
<br />
Password:<br />
<asp:TextBox ID="PasswordTB" runat="server" OnChange="isPassValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidatePassword" runat="server" ForeColor="Red"
Text="Password must be 6-15 characters in length, and contain no special characters." CssClass="Validators"></asp:Label>
<br />
Confirm password:<br />
<asp:TextBox ID="ConfirmTB" runat="server" OnChange="isConfirmValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidateConfirm" runat="server" ForeColor="Red"
Text="This field must match the password field." CssClass="Validators"></asp:Label>
<br />
Email:<br />
<asp:TextBox ID="EmailTB" runat="server" OnChange="isEmailValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidateEmail" runat="server" ForeColor="Red" Text="Invalid Email." CssClass="Validators"></asp:Label>
<br />
<br />
<asp:Button ID="Register" runat="server" Text="Register" onclick="Register_Click" EnableViewState="false"/>
<br />
<asp:Panel ID="Answer" runat="server" >
</asp:Panel>
</asp:Panel>
<br />
<br />
<asp:Panel id="LoginRelated" runat="server">
User:
<asp:TextBox ID="LoginUserTB" runat="server" AutoPostBack="false"></asp:TextBox>
<br />
Password:
<asp:TextBox ID="LoginPassTB" runat="server" AutoPostBack="false"></asp:TextBox>
<br />
<asp:Button ID="Login" runat="server" Text="Login" onclick="Login_Click" EnableViewState="false" />
<br />
</asp:Panel>
<asp:Panel ID="InPage" runat="server">
<asp:Panel ID="LogAnswer" runat="server">
</asp:Panel>
<br />
<asp:Label ID="WelcomeTag" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="logout" runat="server" onclick="logout_Click" Text="Logout" EnableViewState="false"/>
</asp:Panel>
</div>
</form>
</body>
</html>
C# Login, Logout & Register buttons:
protected void Register_Click(object sender, EventArgs e)
{
Label Reply = new Label();
if (Session["User"] == null)
{
Result myRegResult = Result.IN_PROG;
User myAddedUser = new User(UserTB.Text, PasswordTB.Text, EmailTB.Text);
DbManager.OpenDbConnection();
myRegResult = DbManager.Register(myAddedUser); //Connection with the database.
Reply.Text = resultToString(myRegResult);
Reply.ForeColor = resultColor(myRegResult);
}
else
{
Reply.Text = "You must log out before you register.";
Reply.ForeColor = resultColor(Result.EXEC_ERROR);
}
Answer.Controls.Add((Control)Reply);
//Reset_Fields();
}
protected void Login_Click(object sender, EventArgs e)
{
Label Reply = new Label();
LoginProc Status = LoginProc.IN_PROG;
DbManager.OpenDbConnection();
Status = DbManager.Login(LoginUserTB.Text, LoginPassTB.Text); //Connection with the database
Reply.Text = ProcToString(Status);
Reply.ForeColor = ProcToColor(Status);
LogAnswer.Controls.Add(Reply);
if (Status == LoginProc.FINE)
Session["User"] = new User(LoginUserTB.Text, LoginPassTB.Text, null);
//Reset_Fields();
}
protected void logout_Click(object sender, EventArgs e)
{
Session["User"] = null;
}
Page load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
RegisterRelated.Visible = false;
LoginRelated.Visible = false;
InPage.Visible = true;
WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
}
else
{
RegisterRelated.Visible = true;
LoginRelated.Visible = true;
WelcomeTag.Text = String.Empty;
InPage.Visible = false;
}
}
EDIT: A friend of mine adviced me to take a look in the ASP.NET page lifecycle, and it might have something to do with the database interactions being done after the page is presented, if it helps anyone.
Your friend is correct, you need to understand the page the Page Life cycle better. Basically in this instance you need to understand that the OnLoad event happens before any click events. You can see this for yourself by adding a break point to the OnLoad event and the click handler. You will see that the order of events as they happen.
In this instance I would writ a method to set up the page, and then call this in each of the on click events
private void setUpPage()
{
if (Session["User"] != null)
{
RegisterRelated.Visible = false;
LoginRelated.Visible = false;
InPage.Visible = true;
WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
}
else
{
RegisterRelated.Visible = true;
LoginRelated.Visible = true;
WelcomeTag.Text = String.Empty;
InPage.Visible = false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
//Call if not in response to button click
if(!IsPostBack)
{
setUpPage();
}
}
protected void Register_Click(object sender, EventArgs e)
{
Label Reply = new Label();
if (Session["User"] == null)
{
Result myRegResult = Result.IN_PROG;
User myAddedUser = new User(UserTB.Text, PasswordTB.Text, EmailTB.Text);
DbManager.OpenDbConnection();
myRegResult = DbManager.Register(myAddedUser); //Connection with the database.
Reply.Text = resultToString(myRegResult);
Reply.ForeColor = resultColor(myRegResult);
}
else
{
Reply.Text = "You must log out before you register.";
Reply.ForeColor = resultColor(Result.EXEC_ERROR);
}
Answer.Controls.Add((Control)Reply);
//Reset_Fields();
//Reset the fields as required AFTER you have done what you need with the database
setUpPage();
}
protected void Login_Click(object sender, EventArgs e)
{
Label Reply = new Label();
LoginProc Status = LoginProc.IN_PROG;
DbManager.OpenDbConnection();
Status = DbManager.Login(LoginUserTB.Text, LoginPassTB.Text); //Connection with the database
Reply.Text = ProcToString(Status);
Reply.ForeColor = ProcToColor(Status);
LogAnswer.Controls.Add(Reply);
if (Status == LoginProc.FINE)
Session["User"] = new User(LoginUserTB.Text, LoginPassTB.Text, null);
//Reset_Fields();
//Reset the fields as required AFTER you have done what you need with the database
setUpPage();
}
protected void logout_Click(object sender, EventArgs e)
{
Session["User"] = null;
//Reset the fields as required AFTER you have done what you need with the database
setUpPage();
}
When you click the login or register button, page load event works firstly, and after button click event works.
I can see that, you set to page display in page load event and set to Session value in button click event. So at first click, page load event triggered first, but there is no Session value yet. Page load event finishes and resume with button click event, so Session value is not null now (if entered user info is valid).
It is the reason why page work at second click.
Solution:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack) //just write this
return;
if (Session["User"] != null)
{
RegisterRelated.Visible = false;
LoginRelated.Visible = false;
InPage.Visible = true;
WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
}
else
{
RegisterRelated.Visible = true;
LoginRelated.Visible = true;
WelcomeTag.Text = String.Empty;
InPage.Visible = false;
}
}
Note: I got your code and tried.
Also see this: http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.85%29.aspx
I think there is issue with validators. Please set causes validation property of buttons according to your requirements.
Try Page_BlockSubmit = false; before every return false;
Related
I am having this kind of structure in a Web Application where depending on the user's choices Table_1 or Table_2 is given visibility; they never can be both visible.
<table>
<tr><td>
<table id="Table_1" runat="server" visible="false">
<tr><td>...</td></tr>
<tr><td>
<asp:GridView>
<asp:Linkbutton>
<asp:FormView>
</td></tr>
</table>
<table id="Table_2" runat="server" visible="false">
<tr><td>...</td></tr>
<tr><td>
<asp:GridView>
</td></tr>
</table>
</td></tr>
</table>
The strange thing is that this works only if the hole code block for table 2 is on top. If I switch them back to the way described by the code, table_2 never will show up. I do not add anything more. Just by switching the two tables in the code, once the result is correct, while in the other case it isn't.
What can this be related to?
Martin
Code that controls visibility:
protected void GridView01_OnSelectedIndexChanged(object sender, EventArgs e)
{
FilterDDLResponsable.SelectedIndex = -1;
GridView3.Visible = true;
GridView3.EditIndex = -1;
Table_1.Visible = true;
Table_2.Visible = false;
GridView3.DataBind();
ButtonEditMode.Visible = false;
ButtonSendHWReminderSeries.Visible = false;
if (AdminUser.Text == "1")
{
AddButton.Visible = true;
}
LabelAuditID.Text = Convert.ToString(GridView01.SelectedValue);
if(ActivateTabletView.Checked == true)
{
GridView01.Columns[12].Visible = true;
GridView01.Columns[13].Visible = true;
GridView01.Columns[14].Visible = true;
}
else
{
GridView01.Columns[12].Visible = false;
GridView01.Columns[13].Visible = false;
GridView01.Columns[14].Visible = false;
}
FillGrid();
}
and the Grid's row LinkButton onClick method:
protected void OpenAudit(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string AuditID = btn.CommandArgument;
Table_1.Visible = false;
Table_2.Visible = true;
LabelAuditID.Text = AuditID;
foreach (GridViewRow gvRow in GridView01.Rows)
{
if ((int)GridView01.DataKeys[gvRow.DataItemIndex].Value == Convert.ToUInt32(AuditID))
{
GridView01.SelectedIndex = gvRow.DataItemIndex;
break;
}
}
FillQuestionsGrid();
}
I have issues.
One of them is this one.
I'm trying to bind a list of Hyperlinks to a repeater and I think my code looks all good, but my repeater is sadly lacking in anything. It's totally blank (Apart from the header, which is not databound).
I can't see where the problem is, so I'm hoping you guys can point it out to me.
Code:
Markup
<asp:Panel ID="pnlNavMenu" class="navigation" runat="server" Visible="true">
<div class="search-textbox"><div>
<asp:ImageButton ID="btnSearch" class="Search-Icon"
BackColor="White" runat="server" OnClick="btnSearch_Click"
ImageUrl="~/images/Mobile/mobile-search-icon.png" />
<asp:TextBox ID="txtSearch" runat="server" CssClass="Search" onblur="if(this.value == '') { this.value='Enter keyword or product code'; isSet=true; }"
onmouseover="if(this.value == 'Enter keyword or product code') { this.value='';isSet = true; }"
onmouseout="if(this.value == '' && !isSet) { this.value='Enter keyword or product code'; isSet=>false; }"
MaxLength="255" Text="Enter keyword or product code" ontextchanged="btnSearch_Click"/>
<asp:ImageButton ID="btnClear" class="Search-Cancel" BackColor="White" runat="server" OnClick="btnClear_Click" ImageUrl="~/images/Mobile/mobile-search-cancel.png" />
</div>
</div>
<asp:Panel ID="pnlComputers" runat="server" CssClass="nav-item" Visible="true">
<asp:Label id="lblComp" Text="Computers" runat="server" cssclass="Menu-Panel-Header"></asp:Label>
<asp:Repeater ID="rptComputers" runat="server">
<ItemTemplate><asp:HyperLink ID="hlCompCategories" runat="server" CssClass="nav-sub-item"><%#Eval("XW_WEBCATNAME") %></asp:HyperLink></ItemTemplate>
</asp:Repeater>
</asp:Panel
<asp:CollapsiblePanelExtender ID="cpe1" runat="Server" TargetControlID="pnlComputers" CollapsedSize="64" ExpandedSize="192" Collapsed="True" ExpandControlID="lblComp" CollapseControlID="lblComp" AutoCollapse="false" AutoExpand="False" ScrollContents="True" ExpandDirection="Vertical" />
</asp:Panel>
C#
protected void Page_Init(object sender, EventArgs e)
{
if (Session["Customer"] is GPCUser)
{
hlLogInOut.Text = "Log Out";
hlLogInOut.NavigateUrl = "log-in.aspx?logout=1";
hlRegDetails.Text = "My Details";
hlRegDetails.NavigateUrl = "/update-details.aspx";
}
else
{
hlLogInOut.Text = "Log in";
hlLogInOut.NavigateUrl = "/log-in.aspx";
hlRegDetails.Text = "Register";
hlRegDetails.NavigateUrl = "/create-account.aspx";
}
BindCategories();
}
private void BindCategories()
{
if (!IsPostBack)
{
try
{
SqlConnection connect = new SqlConnection();
DataTable Data = new DataTable();
connect.ConnectionString = "SERVER = SERVER-SQL01; Trusted_Connection=yes; DATABASE=PCSQL";
connect.Open();
string query = null;
query = "SELECT * from dbo.STOCK_GROUPS WHERE XW_MAINGROUP = '1' ORDER BY XW_WEBCATNAME ASC";
SqlDataAdapter command = new SqlDataAdapter(query, connect);
command.Fill(Data);
connect.Close();
rptComputers.DataSource = Data;
}
catch (SqlException sqlEX)
{
sqlEX.ToString();
}
}
}
protected void rptComputers_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
HyperLink hlCompCategories = (HyperLink)e.Item.FindControl("hlCompCategories");
DataRowView dr = (DataRowView)e.Item.DataItem;
hlCompCategories.NavigateUrl = Page.ResolveUrl("~/" + "Computers" + "/" + dr["XW_URL"] + "/index.aspx");
if ((!object.ReferenceEquals(dr["xw_webcatname"], System.DBNull.Value)))
{
hlCompCategories.Text = (dr["xw_webcatname"]).ToString();
hlCompCategories.ToolTip = (dr["xw_webcatname"]).ToString();
}
else
{
hlCompCategories.Text = dr["groupname"].ToString();
hlCompCategories.ToolTip = dr["xw_webcatname"].ToString();
}
}
}
I'm pretty sure that the issue is in the ItemDataBound method because the rest of the panel loads fine (search bar and header, etc.) but none of my links are there.
After
rptComputers.DataSource = Data;
add
rptComputers.DataBind();
Otherwise it won't bind.
You might be missing AutoEventWireup=true in Page header in aspx file.
If not than please try to bind the repeater in the Page_Load event instead binding in Page_Init event.
I have the following repeater wrapped in an Update Panel
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:Repeater ID="skillTable" runat="server">
<ItemTemplate>
<table class="table table-hover">
<tr>
<td>
<asp:ImageButton runat="server" AutoPostBack="True" ID="skillButton" OnClick="skillButton_Click" CommandArgument="<%# Eval(DropDownList1.SelectedValue)%>" class="addText btn btn-success" ImageUrl="~/img/addbut.png" /></td>
<td><asp:Label runat="server" id="skillName" Text='<%# DataBinder.Eval(Container.DataItem, DropDownList1.SelectedValue) %>'></asp:Label></td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
It kicks out the information from my database perfectly, and it has a button right before the text in each row.
The problem that i have is that I need each button on each row to, when clicked, add the specific line of code in that row to a textbox.
foreach (RepeaterItem item in skillTable.Items)
{
string skill = item.DataItem.ToString();
string text = skillList.Text;
if (!string.IsNullOrEmpty(text))
{
if (!text.Contains(skill))
{
text += " | " + skill;
skillList.Text = text;
}
}
else
{
text = skill;
skillList.Text = text;
}
}
UpdatePanel2.Update();
I have also tried this way,
protected void skillTable_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
int d = 0;
if(DropDownList1.SelectedValue == "Business and Finance")
{
d = 1;
}
else if(DropDownList1.SelectedValue == "Computers and Technology")
{
d = 2;
}
else if (DropDownList1.SelectedValue == "Education")
{
d = 3;
}
else if (DropDownList1.SelectedValue == "Customer Service")
{
d = 4;
}
DataRowView drv = (DataRowView)e.Item.DataItem;
string skill = drv[d].ToString();
Session["Table"] = skill;
}
protected void skillButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
string skill = (string)(Session["Table"]);
string text = skillList.Text;
if (!string.IsNullOrEmpty(text))
{
if (!text.Contains(skill))
{
text += " | " + skill;
skillList.Text = text;
}
}
else
{
text = skill;
skillList.Text = text;
}
UpdatePanel2.Update();
}
but neither one of them seems to work correctly. Any advice? I havent really used repeaters before this, so If there is any other tool that would work better, I'm open for suggestions.
Thanks in advance!
So I figured it out. What I was missing was a way for my site to specifically narrow down what i needed. I added the code blow to my click method and got rid of the ItemDataBound method and it worked like a charm.
Button button = (sender as Button);
string commandArgument = button.CommandArgument;
RepeaterItem item = button.NamingContainer as RepeaterItem;
var workText = (Label)item.FindControl("workName1") as Label;
string work = workText.Text;
string text = workDetails1.Text;
if (text == " ")
text = "";
if (text == "")
{
if (!text.Contains(work))
{
text +="\u2022 " + work;
workDetails1.Text = text;
}
}
else if (!string.IsNullOrEmpty(work))
{
if (!text.Contains(work))
{
text += "\n\u2022 " + work;
workDetails1.Text = text;
}
else
{
workDetails1.Text = text;
}
}
UpdatePanel4.Update();
Hope this helps someone!
My registration used to be working completely fine, but I have since done multiple modifications to it, so I can't find out what has caused this problem...
When I enter details and click Register, the page takes a long time to process, using the asp.net local server. It then finally says I've registered, but has entered 10-30 entries into the database (some aren't even identical, with different fields missing etc)
I can clear all the created entries in the database, then re-open it, and it has added 10-30 more... it will keep doing this until I kill the asp.net development server it creates when I "start without debugging".
Here is the c# file for the page:
using System;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
//Display welcome message
lblMessage.Text = "Welcome " + txtFirstName.Text + "!";
//Save the registration data into database, 17/8/2014
SaveRegistration();
sendEmail();
}
}
private void SaveRegistration()
{
OleDbConnectionStringBuilder sb = new OleDbConnectionStringBuilder();
sb.Provider = "Microsoft.ACE.OLEDB.12.0";
//sb.DataSource = Server.MapPath("/carpec02/asp_assignment/App_Data/shoeDB.accdb");
sb.DataSource = Server.MapPath("~/App_Data/shoeDB.accdb");
OleDbConnection myConnection = new OleDbConnection(sb.ConnectionString);
string queryString = "";
OleDbCommand myCmd = new OleDbCommand(queryString, myConnection);
//Open connection
myConnection.Open();
//Build the query string
StringBuilder queryStringBuilder = new StringBuilder("Insert into customer([customerFirstName], [customerLastName], [customerPassword], [customerPhHome], [customerPhWork], [customerPhMobile], [customerEmail], [customerPrivilege], [customerUsername])");
queryStringBuilder.Append("values ('");
queryStringBuilder.Append(txtFirstName.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtLastName.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtPassword.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtPhHome.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtPhWork.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtPhMobile.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtEmail.Text);
queryStringBuilder.Append("','");
queryStringBuilder.Append("User");
queryStringBuilder.Append("','");
queryStringBuilder.Append(txtUsername.Text);
queryStringBuilder.Append("')");
queryString = queryStringBuilder.ToString();
//Assign the QueryString to the command object
myCmd.CommandText = queryString;
//Execute the query
myCmd.ExecuteNonQuery();
//Create another command object to display the inserted record ID
OleDbCommand anotherCmd = new OleDbCommand("SELECT ##IDENTITY", myConnection);
int numId = Convert.ToInt32(anotherCmd.ExecuteScalar());
lblDataId.Text = "<h3>Your registration number is <big>" + numId.ToString() + "</big></h3>";
//Close the connection
myConnection.Close();
}
//Modified from http://www.aspsnippets.com/Articles/How-to-create-Contact-Us-Page-in-ASPNet.aspx
protected void sendEmail()
{
try
{
string strReceiver = txtEmail.Text;
MailMessage mm = new MailMessage("fakeemail#gmail.com", strReceiver); //Sender / receiver
mm.Subject = "Welcome to Awesome Shoes!";
mm.Body = "Thank you, " + txtFirstName.Text + " " + txtLastName.Text + ", for registering at Awesome Shoes. Your username is: " + txtUsername + " and your password is " + txtPassword;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "fakeemail#gmail.com";
NetworkCred.Password = "fake123";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
lblMessage2.Text = "Email Sent Sucessfully.";
}
catch
{
}
}
}
and here is the asp.net code for the page:
<%# Page Title="" Language="C#" MasterPageFile="~/AwesomeShoes.master" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TabTitle" Runat="Server">
Register - Awesome Shoes
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Head" Runat="Server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="CurrentTabRegister" Runat="Server">
class="currentTab"
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainTitle" Runat="Server">
Register
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="MainBody" Runat="Server">
<script type="text/javascript">
function IsInteger(input) {
var regEx = /^\+{0,1}\d+\d*$/;
return regEx.test(input);
}
function btnRegister_OnClick()
{
var txtFirstName = document.getElementById('MainBody_txtFirstName');
if (txtFirstName.value.length == 0)
{
alert("You must enter all the required information before submitting");
return;
}
var txtEmail = document.getElementById('MainBody_txtEmail');
if (txtEmail.value.indexOf('#') == -1)
{
alert("You must enter an # for your email address.");
return;
}
var txtPassword = document.getElementById('MainBody_txtPassword');
if (txtPassword.value.length < 6) {
alert("Your password must be at least 6 characters long");
return;
}
var txtRepeatPassword = document.getElementById('MainBody_txtRepeatPassword');
if (txtRepeatPassword.value != txtPassword.value) {
alert("Your password does not match");
return;
}
var txtPhHome = document.getElementById('MainBody_txtPhHome');
var txtPhWork = document.getElementById('MainBody_txtPhWork');
var txtPhMobile = document.getElementById('MainBody_txtPhMobile');
if ((!IsInteger(txtPhHome.value)) && (!IsInteger(txtPhWork.value)) && (!IsInteger(txtPhMobile.value)))
{
alert('You must enter at least one phone number.');
return;
}
if (IsInteger(txtPhHome.value))
{
if (txtPhHome.value < 1000000 || txtPhHome.value > 9999999) {
alert('The home phone number you entered is invalid. It must be between 100-0000 and 999-9999');
return;
}
}
if (IsInteger(txtPhWork.value)) {
if (txtPhWork.value < 1000000 || txtPhWork.value > 9999999) {
alert('The work phone number you entered is invalid. It must be between 100-0000 and 999-9999');
return;
}
}
if (IsInteger(txtPhMobile.value)) {
if (txtPhMobile.value < 0210000000 || txtPhMobile.value > 0299999999) {
alert('The mobile phone number you entered is invalid. It must be between 021-000-0000 and 029-999-9999');
return;
}
}
document.getElementById('form1').submit();
}
</script>
<div>
<table>
<tr><td>First Name:</td><td><asp:TextBox ID="txtFirstName" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>last Name:</td><td><asp:TextBox ID="txtLastName" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Username:</td><td><asp:TextBox ID="txtUsername" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Password:</td><td><asp:TextBox ID="txtPassword" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Repeat Password:</td><td><asp:TextBox ID="txtRepeatPassword" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Email:</td><td><asp:TextBox ID="txtEmail" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Home Phone:</td><td><asp:TextBox ID="txtPhHome" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Work Phone:</td><td><asp:TextBox ID="txtPhWork" Width="150" runat="server"></asp:TextBox></td></tr>
<tr><td>Mobile Phone:</td><td><asp:TextBox ID="txtPhMobile" Width="150" runat="server"></asp:TextBox></td></tr>
</table>
<input type="button" class="caption" value="Register" id="btnRegister" name="btnRegister" onclick="btnRegister_OnClick()"/>
<br/>
<asp:Label ID="lblMessage" runat="server" class="message"></asp:Label>
<br/>
<asp:Label ID="lblMessage2" runat="server" class="message"></asp:Label>
<br/>
<asp:Label ID="lblDataId" runat="server"></asp:Label>
</div>
</asp:Content>
Appreciate any help as to why this may be happening, as the assignment is due later today.
Instead of passing these methods in Page Load, write them into the button click event as.
protected void btnRegister_Click(object sender, EventArgs e)
{
//Save the registration data into database, 17/8/2014
SaveRegistration();
sendEmail();
}
Change the html markup of Register button as,
<asp:Button type="button" CssClass="caption" Text="Register" ID="btnRegister" onclick="btnRegister_Click" onClientClick="javascript:btnRegister_OnClick();"/>
I have a TabContainer in my aspx page as follows
<asp:TabContainer ID="tabcontainer" runat="server" ActiveTabIndex="0">
</asp:TabContainer>
am creating the tabs for the above containter using C# code on Oninit event of the page
protected override void OnInit(EventArgs e)
{
lstCategories = Service.GetCategories();
numberOfCategories = lstCategories.Count;
CreateTabs();
base.OnInit(e);
}
protected void CreateTabs()
{
try
{
for (int i = 0; i < numberOfCategories; i++)
{
TabPanel asptab = new TabPanel();
asptab.ID = lstCategories[i].Id.ToString();
asptab.HeaderText = lstCategories[i].Name;
MyCustomTemplate obj = new MyCustomTemplate(lstCategories[i].Id);
asptab.ContentTemplate = obj;
tabcontainer.Tabs.Add(asptab);
}
}
catch (Exception ex)
{
}
}
public class MyCustomTemplate : ITemplate
{
public Table tbl;
public TextBox tbxQuantity;
public Image img;
public int countOfItemsPerRow = 2;
public MyCustomTemplate(int paramCategoryID)
{
categoryID = paramCategoryID;
}
public void InstantiateIn(Control container)
{
InitialiseTheProperties();
container.Controls.Add(tblHardware);
}
public Table InitialiseTheProperties()
{
//Intialize the Mater Table
tbl = new Table();
//Create Row for the mater Table
TableRow row = new TableRow();
TableCell cell = new TableCell();
img = new Image();
img.ImageUrl = HttpRuntime.AppDomainAppVirtualPath +"/Images/"+"1.jpg";
cell.Controls.Add(img);
tblHardware.Rows.cells.add(cell);
tbxQuantity = new TextBox();
tbxQuantity.ID ="TbxQuantity";
cell.Controls.Add(tbxQuantity);
tblHardware.Rows.cells.add(cell);
tblHardware.Rows.Add(row);
//return tbl;
}
}
}
now am trying to this on a btnclickevent
public void btnSave_Click(object sender, EventArgs e)
{
try
{
Control cntrl = Page.FindControl("TbxQuantity");
}
catch (Exception ex)
{
}
}
it just returns null. Am i doing something wrong? Kindly Help
As i found the answer to the above question posted by myself, I would like to help fellow folks who encounter the same or similar problem.
string strQuantity=((System.Web.UI.WebControls.TextBox)(((AjaxControlToolkit.TabContainer)(BTN.Parent.FindControl("tabcontainer"))).Tabs[0].FindControl("TbxQuantity"))).Text
Thank you "Stackoverflow" for maintaining the site and I also thank the members who help developers like me.
Your issue isn't with the dynamically added controls, but that the FindControl method doesn't propogate and check all the way down the children stack.
I made a quick helper method below that checks the children until it finds the right control. It was a quick build, so it probably can be improved upon, I haven't tried but you could probably extend the control so you don't have to pass in an initial control. I tested it, however for some reason I couldn't get it to work passing in the Page object, I had to pass in the initial panel I used, but it should get the point across.
Control Finder
public static class ControlFinder
{
public static Control Find(Control currentControl, string controlName)
{
if (currentControl.HasControls() == false) { return null; }
else
{
Control ReturnControl = currentControl.FindControl(controlName);
if (ReturnControl != null) { return ReturnControl; }
else
{
foreach (Control ctrl in currentControl.Controls)
{
ReturnControl = Find(ctrl, controlName);
if (ReturnControl != null) { break; }
}
}
return ReturnControl;
}
}
}
HTML Page
<asp:Panel ID="pnl1" runat="server">
<asp:TextBox ID="pnl1_txt1" runat="server" />
<asp:TextBox ID="pnl1_txt2" runat="server" />
<asp:Panel ID="pnl2" runat="server">
<asp:TextBox ID="pnl2_txt1" runat="server" />
<asp:TextBox ID="pnl2_txt2" runat="server" />
<asp:Panel ID="pnl3" runat="server">
<asp:TextBox ID="pnl3_txt1" runat="server" />
<asp:TextBox ID="pnl3_txt2" runat="server" />
</asp:Panel>
</asp:Panel>
</asp:Panel>
<asp:Button ID="btnGo" Text="Go" OnClick="btnGo_Click" runat="server" />
<asp:Panel ID="pnlResults" runat="server">
<div>pnl1_txt1: <asp:Label ID="lblpnl1txt1" runat="server" /></div>
<div>pnl1_txt2: <asp:Label ID="lblpnl1txt2" runat="server" /></div>
<div>pnl2_txt1: <asp:Label ID="lblpnl2txt1" runat="server" /></div>
<div>pnl2_txt2: <asp:Label ID="lblpnl2txt2" runat="server" /></div>
<div>pnl3_txt1: <asp:Label ID="lblpnl3txt1" runat="server" /></div>
<div>pnl3_txt2: <asp:Label ID="lblpnl3txt2" runat="server" /></div>
<div>unknown: <asp:Label ID="lblUnknown" runat="server" /></div>
</asp:Panel>
Button Click event
protected void btnGo_Click(object sender, EventArgs e)
{
Control p1t1 = ControlFinder.Find(pnl1, "pnl1_txt1");
Control p1t2 = ControlFinder.Find(pnl1, "pnl1_txt2");
Control p2t1 = ControlFinder.Find(pnl1, "pnl2_txt1");
Control p2t2 = ControlFinder.Find(pnl1, "pnl2_txt2");
Control p3t1 = ControlFinder.Find(pnl1, "pnl3_txt1");
Control p3t2 = ControlFinder.Find(pnl1, "pnl3_txt2");
Control doesntexist = ControlFinder.Find(pnl1, "asdasd");
lblpnl1txt1.Text = p1t1 != null ? "Found: " + p1t1.ID : "Not found";
lblpnl1txt2.Text = p1t2 != null ? "Found: " + p1t2.ID : "Not found";
lblpnl2txt1.Text = p2t1 != null ? "Found: " + p2t1.ID : "Not found";
lblpnl2txt2.Text = p2t2 != null ? "Found: " + p2t2.ID : "Not found";
lblpnl3txt1.Text = p3t1 != null ? "Found: " + p3t1.ID : "Not found";
lblpnl3txt2.Text = p3t2 != null ? "Found: " + p3t2.ID : "Not found";
lblUnknown.Text = doesntexist != null ? "Found: " + doesntexist.ID : "Not found";
}