Im making a website that sends information to a mysql server, using asp.net. code. The problem Im having is that when i debug the code and launch the page, I get these error:
Im not sure why, I have this error.
Here is my code:
Default.aspx
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<form id="form1" runat="server">
<div>
<table width="300px" >
<tr>
<td>First Name</td>
<td>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td >Last Name</td>
<td>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>User Name</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Email Address</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:Label ID="lblError" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</asp:Content ID="Content1" runat="server" ContentPlaceHolderID="MainContent">
Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
string cnnString = "Server=localhost;Port=1111;Database=ci_series;Uid=asdfasdf;Pwd=*******";
MySqlConnection connection = new MySqlConnection(cnnString);
string cmdText = "INSERT INTO membership (first_name ,last_name ,username ,password ,";
cmdText += "email_address)VALUES (first_name ,last_name ,username ,password ,email_address);";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("?first_name", MySqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.Add("?last_name", MySqlDbType.VarChar).Value = txtLastName.Text;
cmd.Parameters.Add("?username", MySqlDbType.VarChar).Value = txtUserName.Text;
cmd.Parameters.Add("?password", MySqlDbType.VarChar).Value = txtPassword.Text;
cmd.Parameters.Add("?email_address", MySqlDbType.VarChar).Value = txtEmail.Text;
connection.Open();
int result = cmd.ExecuteNonQuery();
lblError.Text = "Data Saved";
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
}
How Do i Fix this? What does "Not exist in the current context" mean? Thanks in advance!
1) Make sure runat="server" is on the html tag on your master page.
2) Sometimes you get this error due to and assembly caching problem because VS gets confused about what actually needs to be recompiled. -- I just delete the cache items and recompile normally, figuring that more than 1 thing may be wrong
You have 2 issues
</asp:Content> instead </asp:Content ID="Content1" runat="server" ContentPlaceHolderID="MainContent"> . It's already put the comment from piLHa
You don't need form tagin content page . the form tag was already defined in master page , so please remove the form tag in your content page.
I had a similar issue when getting old VS2005 aspx/aspx.cs files into a new project in VS2013. I resolved this by creating a new web application, creating a new webform for each aspx page and copying the code for .aspx and .cs. Once copied I have to change the .cs files first line to use CodeBehind instead of CodeFile .
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="_Login" %>
TO
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="_Login" %>
I hope this helps someone else.
I got same problem when i was coding with c# aspx and i figured out this like that:
I had deleted this Inherits="project_name.ClassName" from my XXX.aspx file mistakenly which is first line in my XXX.aspx file.. And then when i added Inherits="project_name.ClassName" this code to my XXX.aspx first line to my file and then it solved my problem. You should make control your first line in your XXX.aspx file, you could delete Inherits="project_name.ClassName" wrongly....
I hope you will figure out the problem for this answer.
Good luck
Replace below code of .aspx page in #page tag
Replace this: <%# Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Namespace.Test" %>
Replace with: <%# Page Language="C#" AutoEventWireup="true" CodeFile="~/Test.aspx.cs" CodeBehind="Test.aspx.cs" Inherits="Namespace.Test" %>
Right_click on "WebApplication"
and Click on "Convert to Web Application "
Related
I need the fix for CSRF flaw for aspx page. The code is like this -
ASPX -
<asp:Content runat='server'>
<asp:Panel runat='server'>
<table>
<tr>
<td>Username</td>
<td><asp:TextBox runat="server" ID="Username" autocomplete="off"></asp:TextBox></td>
</tr>
<tr>
<td>Password</td>
<td><asp:TextBox runat="server" ID="Password" TextMode="Password" autocomplete="off"></asp:TextBox></td>
</tr>
<tr>
<asp:Button ID="Submit" runat="server" Text="Submit"
OnClick="SubmitButton_Click" CssClass="Resizable" />
</tr>
</table>
</asp:Panel>
</asp:Content>
ASPX.cs -
protected void SubmitButton_Click(object sender, EventArgs e)
{
//Code here
}
Now while inserting <%# Html.AntiForgeryToken() %> at the top throws error "The server block is not well formed". So how should I proceed with the fix.
You're using webforms here. They already have anti-xsrf set up in the template of the master page (I think it's tucked in with all of the viewstate data).
So as long as you are using a master page then you needn't worry.
If you're not using a master page just build your own using session state, a hidden field and a guid. I've taken the below from http://willseitz-code.blogspot.com/2013/06/cross-site-request-forgery-for-web-forms.html
Your hiddenfield...
<asp:HiddenField ID="antiforgery" runat="server"/>
The code that does the work server side...
public static class AntiforgeryChecker
{
public static void Check(Page page, HiddenField antiforgery)
{
if (!page.IsPostBack)
{
Guid antiforgeryToken = Guid.NewGuid();
page.Session["AntiforgeryToken"] = antiforgeryToken;
antiforgery.Value = antiforgeryToken.ToString();
}
else
{
Guid stored = (Guid) page.Session["AntiforgeryToken"];
Guid sent = new Guid(antiforgery.Value);
if (sent != stored)
{
throw new SecurityException("XSRF Attack Detected!");
}
}
}
}
And finally the following in your Page_Load method in code behind...
AntiforgeryChecker.Check(this, antiforgery);
I have a website in ASP.NET and I have a textbox that the user type in text. I want to save this into a SQL Server database that saves all other data from site. I have tried several ways and got to the code below. It throws up the error below
Any help as I'm lost on this now....
Error:
The name 'txtName' does not exist in the current context Step9.aspx.cs 67
Page markup:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Step9.aspx.cs" Inherits="Step1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="question" id="question">
<table border="1" style="border-collapse: collapse">
<tr>
<td style="width: 150px">
Name:<br />
<asp:TextBox ID="txtName" runat="server" Width="140" />
</td>
<td style="width: 100px">
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
</td>
</tr>
</table>
</div>
</asp:Content>
C# codebehind:
protected void Insert(object sender, EventArgs e)
{
string name = txtName.Text;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO learners (stickTwistBefore) VALUES (#stickTwistBefore)"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Parameters.AddWithValue("#stickTwistBefore", name);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
// this.BindGrid();
}
I noticed that you have specified Step1 class name as Inherits attribute. Ensure that it matches the class name in your Step9.aspx.cs file. I guess Step9 but just confirm.
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Step9.aspx.cs" Inherits="Step1" %>
I have a label and a text box which i have added in the user control.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddMultiLoc.ascx.cs" Inherits="CRM_Streamline_Forms.UserControls.AddMultiLoc" %>
<table>
<tr>
<td style="width:25%">
<asp:Label ID="lblLocName_UC_G0138" runat="server" Text="Location Name:" />
</td>
<td style="width:25%">
<asp:TextBox ID="txtLocName_UC_G0138" runat="server" Width="200px" />
</td>
<td style="width:25%">
<asp:Label ID="lblLocID_UC_G0138" runat="server" Text="Location ID:" />
</td>
<td style="width:25%">
<asp:TextBox ID="txtLocID_UC_G0138" runat="server" Width="200px" />
</td>
</tr>
I have a link button in one of my aspx pages which is when clicked should populate this user control.
<asp:LinkButton ID="lnkAddLoc_AGBI2_G0138" runat="server" Text="+ Add Another Location" onclick="lnkAddLoc_AGBI2_G0138_Click" />
Code behind, I have written this code for the button click:
protected void lnkAddLoc_AGBI2_G0138_Click(object sender, EventArgs e)
{
AddMultiLoc con = (AddMultiLoc)LoadControl("~/UserControls/AddMultiLoc.ascx");
pnlMultiInvoiceInfo1_AGBI2_G0138.Controls.Add(con);
Panel p = new Panel();
Control uc = (Control)Page.LoadControl("~/UserControls/AddMultiLoc.ascx");
p.Controls.Add(uc);
p.Width = 200;
p.Height = 100;
pnlMultiInvoiceInfo1_AGBI2_G0138.Controls.Add(p);
}
First time the user control is populated as am calling it in the aspx page, but second time when i click on the link button, it is not populating the user control for the second time. Am new to coding, please help :(
The problem I think is that you are losing your controls across postback as the controls are loaded in to the ViewState.
Here is a sample where you can load the controls in to the Session which is not really good practice but it will work for your purposes:
AddMultiLocPage.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton ID="lnkAddLoc_AGBI2_G0138" runat="server" Text="+ Add Another Location" OnClick="lnkAddLoc_AGBI2_G0138_Click" />
</div>
<asp:PlaceHolder runat="server" ID="Placeholder1"></asp:PlaceHolder>
</form>
</body>
</html>
AddMultiLocPage.aspx.cs
public partial class AddMultiLocPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoadControlsFromSession();
}
private List<AddMultiLoc> ViewStateControls
{
get { return (List<AddMultiLoc>) Session["ViewStateControls"]; }
set { Session["ViewStateControls"] = (List<AddMultiLoc>)value; }
}
private void LoadControlsFromSession()
{
if (ViewStateControls != null)
{
Placeholder1.Controls.Clear();
foreach (var c in ViewStateControls)
{
Placeholder1.Controls.Add(c);
}
}
}
protected void lnkAddLoc_AGBI2_G0138_Click(object sender, EventArgs e)
{
var con = (AddMultiLoc)LoadControl("~/AddMultiLoc.ascx");
con.ID = Guid.NewGuid().ToString();
List<AddMultiLoc> tmpList = ViewStateControls;
if(tmpList == null) tmpList = new List<AddMultiLoc>();
tmpList.Add(con);
ViewStateControls = tmpList;
LoadControlsFromSession();
}
}
UserControl Markup
<table>
<tr>
<td style="width: 25%">
<asp:Label ID="lblLocName_UC_G0138" runat="server" Text="Location Name:" />
</td>
<td style="width: 25%">
<asp:TextBox ID="txtLocName_UC_G0138" runat="server" Width="200px" />
</td>
<td style="width: 25%">
<asp:Label ID="lblLocID_UC_G0138" runat="server" Text="Location ID:" />
</td>
<td style="width: 25%">
<asp:TextBox ID="txtLocID_UC_G0138" runat="server" Width="200px" />
</td>
</tr>
</table>
No need to store control in session, Solution to your problem is :
ASPX Code :
< asp:LinkButton ID="lnkAddLoc_AGBI2_G0138" runat="server" Text="+ Add Another Location" onclick="lnkAddLoc_AGBI2_G0138_Click" />
<asp:Panel ID="Panel1" runat="server">
Code Behind :
protected void lnkAddLoc_AGBI2_G0138_Click(object sender, EventArgs e)
{
Control uc = (Control)Page.LoadControl("~/AddMultiLoc.ascx");
Panel1.Controls.Add(uc);
}
Any time you click on link button lnkAddLoc_AGBI2_G0138 it add new instance of User Control to Panel1.
I'm using a CreateUserWizard control and I want to customize it to meet my requirements.
My question is: it possible using the CreateUserWizard control to move the Email textbox to another step then the CreateUserWizardStep step?
What I want to achieve is from the step #1 to have the UserName, Password and ConfirmPassword and on Step #2 the Email, a custom ConfirmEmail, SecurityQuestion/SecurityAnswer and other information.
I know how to add a wizard step but if I move any of the default textbox I'm getting an error about missing field in the CreateUserWizard step.
I suggest you to test with this structure
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" >
<WizardSteps>
<asp:CreateUserWizardStep runat="server">
.....
</asp:CreateUserWizardStep>
<asp:WizardStep runat="server">
...
</asp:WizardStep>
<asp:CompleteWizardStep runat="server" />
</WizardSteps>
</asp:CreateUserWizard>
Control of validating with ValidationGroup property, in order to activate validating just when needed
Link : http://msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.button.validationgroup.aspx
After posting the question I start to try some alternative I havent think about. Like adding a WizardStep on top of the CreateUserWizard step where I have UserNameTextBox, PasswordTextBox and ConfirmPasswordTextBox.
The CreateUserWizard step contains a hiden UserName, Password and ConfirmPassword textbox which I set the values on ActiveStepChanged event. that step also contains the other required fields to create the user sich as Question and answer.
This meet my requirements and I am a happy programmer :)
Here I'm showing how to customized create user wizard & I'm using Microsoft Visual Studio Express 2013 For Web
In your register.aspx Page
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" OnCreatedUser="CreateUserWizard1_CreatedUser" CreateUserButtonText="Submit">
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep" runat="server">
<ContentTemplate>
<table>
<tr>
<td>User name:
</td>
<td>
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Password:
</td>
<td>
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><asp:TextBox ID="ConfirmPassword" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr class="form-group">
<td>E-mail:
</td>
<td >
<asp:TextBox ID="Email" runat="server" TextMode="Email"></asp:TextBox>
</td>
</tr>
<tr>
<td>First Name:
</td>
<td>
<asp:TextBox ID="FirstName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Last Name:
</td>
<td>
<asp:TextBox ID="LastName" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</ContentTemplate>
</asp:CreateUserWizardStep>
<asp:CompleteWizardStep runat="server"></asp:CompleteWizardStep>
</WizardSteps>
</asp:CreateUserWizard>
And CreateUserWizard1_CreatedUser code behind your Register.aspx.cs file use this code
var manager = new UserManager();
var user = new ApplicationUser() { UserName = CreateUserWizard1.UserName };
IdentityResult result = manager.Create(user, CreateUserWizard1.Password);
// Get the UserId of the just-added user
MembershipUser newUser = Membership.GetUser(CreateUserWizard1.UserName);
Guid newUserId = (Guid)newUser.ProviderUserKey;
//Get Profile Data Entered by user in Create User Wizard control
String FirstName = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("FirstName")).Text;
String LastName = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("LastName")).Text;
// Insert a new record into User_Profile
// Get your Connection String from the web.config. MembershipConnectionString is the name I have in my web.config
string connectionString = ConfigurationManager.ConnectionStrings["yourConnectionstring"].ConnectionString;
string insertSql = "INSERT INTO yourDBTableName(dbTcolumn,dbTcolumn, dbTcolumn) values(#dbTcolumn, #dbTcolumn)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.Parameters.AddWithValue("#dbTcolumn", FirstName);
myCommand.Parameters.AddWithValue("#dbTcolumn", LastName);
myCommand.Parameters.AddWithValue("#dbTcolumn", newUserId);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
Here I'm not using RequiredFieldValidator. If you want to use, Just use Register.aspx page this bellow section
<asp:RequiredFieldValidator Display="Dynamic" ID="RequiredFieldValidator4" runat="server"
ControlToValidate="FirstName" ErrorMessage="The user name field is required." ValidationGroup="CreateUserWizard1"></asp:RequiredFieldValidator>
and add CreateUserWizard1_CreatedUser code behind if (result.Succeeded) in your Register.aspx.cs
I hope this is help to you customized your create user wizard.
Thanks
I have a page that has some server controls in it. For some reason these controls are null in the page's Page_Load event handler.
<asp:Content ID="mainContent" runat="server" ContentPlaceHolderID="mainPlaceholder">
<asp:Label ID="userIdLockedLabel" runat="server" EnableViewState="False" ForeColor="Red"
Visible="False">
</asp:Label>
<asp:Panel ID="standardLoginPanel" runat="server">
<asp:Login ID="loginControl" runat="server"
DisplayRememberMe="false"
PasswordRecoveryUrl="?action=lostpass"
TextBoxStyle-Font-Names="verdana"
TextBoxStyle-Font-Size="Small"
DestinationPageUrl="Home.aspx"
OnLoggingIn="OnLoggingIn"
OnLoginError="OnError"
TitleText="" >
<TextBoxStyle Font-Names="verdana" Font-Size="Small"></TextBoxStyle>
<LoginButtonStyle CssClass="btn" />
</asp:Login>
</asp:Panel>
<asp:Panel ID="canadaLoginPanel" runat="server" Visible="false">
<asp:Label ID="userFailureLabel" runat="server"></asp:Label>
<table>
<tr>
<td><%= Utility.RetrieveResource("CompanyNumberLabel") %></td>
<td><asp:TextBox ID="companyNumberTextbox" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><%= Utility.RetrieveResource("UserIdLabel")%></td>
<td><asp:TextBox ID="userIdTextbox" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><%= Utility.RetrieveResource("PasswordLabel")%></td>
<td><asp:TextBox ID="userPasswordTextbox" runat="server" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2">
<asp:CheckBox ID="rememberMeCheckBox" runat="server" />
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center"><asp:Button ID="userSubmit" runat="server" CssClass="btn" /></td>
</tr>
<tr>
<td colspan="2" style="text-align:center"><%= Utility.RetrieveResource("ForgotPasswordLinkText") %></td>
</tr>
</table>
</asp:Panel>
<br />
<div style="font-family: Verdana; font-size: small">
<span class="bold">
<%= Utility.RetrieveResource("TroubleLogginIn") %>
</span><br />
<%= Utility.RetrieveResource("ForgotPasswordText") %>
</div>
The page, login.aspx inherits from LogOnBasePage, and that is where the Page_Load code is. In there, I use the following code:
if (this.Company.SiteType == Ceridian.KB.Entities.SiteType.CAN)
{
this.FindControlRecursive("standardLoginPanel").Visible = false;
this.FindControlRecursive("canadaLoginPanel").Visible = true;
((Button)this.FindControlRecursive("userSubmit")).Text = Utility.RetrieveResource("LoginButtonText");
this.Login = null;
CheckBox rememberMe = (CheckBox)this.FindControlRecursive("rememberMeCheckBox");
rememberMe.Text = Utility.RetrieveResource("RememberMeText");
}
Here is the content of the FindControlRecursive method.
public static Control FindControlRecursive(this Control control, string controlId)
{
if (string.Compare(control.ID, controlId, StringComparison.OrdinalIgnoreCase) == 0)
{
// We found the control!
return control;
}
else
{
// Recurse through ctrl's Controls collections
foreach (Control child in control.Controls)
{
Control lookFor = FindControlRecursive(child, controlId);
if (lookFor != null)
{
// We found the control
return lookFor;
}
}
// If we reach here, control was not found
return null;
}
}
I always get a null reference on the first line inside the if check. I don't see how this is possible.
It might be that you need to wait later in the page lifecycle. try putting it in the page_prerendercomplete event like this
Page_PreRenderComplete(Object sender, EventArgs e)
{
if (this.Company.SiteType == Ceridian.KB.Entities.SiteType.CAN)
{
this.FindControlRecursive("standardLoginPanel").Visible = false;
this.FindControlRecursive("canadaLoginPanel").Visible = true;
((Button)this.FindControlRecursive("userSubmit")).Text = Utility.RetrieveResource("LoginButtonText");
this.Login = null;
CheckBox rememberMe = (CheckBox)this.FindControlRecursive("rememberMeCheckBox");
rememberMe.Text = Utility.RetrieveResource("RememberMeText");
}
Does the page you are inheriting from use a markup file (e.g. LogOnBasePage.aspx)?
If so then I think you are out of luck inheriting from it. The markup page generates a class that inherits from the class defined in the code behind page. One of the responsibilities of this generated class is to instantiate the controls defined in the markup. If you inherit from LogOnBasePage your new page will not have the code necessary to instantiate the controls from LogOnBasePage markup and therefore you will get null references.