The name 'UName' does not exist in the current context - c#

When trying to register to my database I am receiving the "The name 'UName' does not exist in the current context" error.
Register.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Registration Page</title>
</head>
<body>
<p>This is the registration page</p>
Home | Register
<form id="form1" runat="server">
<div>
<p>Enter First Name :</p>
<p>
<asp:TextBox ID="UName" runat="server" Width="271px"></asp:TextBox>
</p>
<p>
<asp:Button ID="registerButton" runat="server" Text="REGISTER" OnClick="registerEventMethod" />
</p>
</div>
</form>
</body>
</html>
Register.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Register : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
String queryStr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void registerEventMethod(object sender, EventArgs e)
{
registerUser();
}
private void registerUser()
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO jamieobr_obecarrentals.users (Forename)" +
"VALUES('" + UName.Text + "')";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
}
}
why am I getting this error? I have tried several solutions and all failed.

So I solved my own issue, the first initial issue was that I tried copying the .aspx file into a new solution, however this did not copy along the .aspx.designer.cs file therefore causing the problem.
However after trying to re write a fresh version manually which had a designer file with it I forgot to include the .cs file into the namespace of my solution therefore then generating a new problem.
However after including the .cs file into the namespace, hey presto, it worked!

Related

GETTING ERROR IN SIGN UP PAGE for inserting values in SQL server DATABASE table through webform TEXTBOX

hi I am trying to make a log in page as well as sign up page in asp.net using 3 tier architecture by using sql server architecture. I am able to fetch data from sql server data base which I have manually inserted during table creation in database and I am able to use it in my log in page.
I have also created a sign up page but I am not able to get the values from sign up webform textbox to sqlserver database I am getting some error kindly help me with this.
I have given the connection string of sql server in web.config
my sql server table creation code
CREATE TABLE LOGINDETAILS
(USERID VARCHAR(50),
PASSWORD VARCHAR (50)
);
INSERT INTO LOGINDETAILS (USERID,PASSWORD) values( 'sam', 'pass');
web.config connection string code
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="DBcon" connectionString="Data Source=P3A-B1YH882\SQLSERVER;Initial Catalog=master;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
my business layer /middle layer code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using DataAcess;
using System.Data.SqlClient;
using System.Data.Sql;
namespace middlelayer
{
public class UserBO
{
private string _UserName = " ";
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
private string _Password = " ";
public string Password
{
get { return _Password; }
set { _Password = value; }
}
DataA da = new DataA();
public bool getUser()
{
if (da.IsValid(UserName, Password).Tables[0].Rows.Count == 0)
{
return false;
}
else
{
return true;
}
}
}
}
my datAccess layer code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
namespace DataAcess
{
public class DataA
{
string conString = ConfigurationManager.ConnectionStrings["DBcon"].ToString();
public DataSet IsValid(string UserName, string Password)
{
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM LOGINDETAILS WHERE USERID ='" + UserName + "' and PASSWORD= '" + Password + "'", con);
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
return ds;
}
}
}
MY LOGIN PAGE CODE
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="WebApplication4.login" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="height: 277px">
<form id="form1" runat="server">
<div>
<asp:Label ID="lbluserid" runat="server" BackColor="#FFFF99" BorderStyle="Ridge" Height="17px" Text="User ID" Width="52px"></asp:Label>
<asp:TextBox ID="txtuserid" runat="server" BackColor="#99FFCC" style="margin-left: 122px"></asp:TextBox>
<br />
</div>
<p>
<asp:Label ID="lblpassword" runat="server" BackColor="#FFFF99" BorderStyle="Ridge" Text="Password"></asp:Label>
<asp:TextBox ID="txtpassword" TextMode="Password" runat="server" BackColor="#99FFCC" style="margin-left: 110px" ></asp:TextBox>
</p>
<p>
</p>
<asp:Button ID="btnlogin" runat="server" BackColor="#33CCFF" BorderStyle="Ridge" OnClick="btnlogin_Click" style="margin-left: 78px" Text="Login" Width="107px" />
<p>
</p>
<asp:Label ID="Label1" runat="server" Text="NOT REGISTERED ??"></asp:Label>
<asp:HyperLink ID="HyperLink1" runat="server" BorderStyle="Outset" NavigateUrl="~/sign_up.aspx">SIGN UP</asp:HyperLink>
</form>
</body>
</html>
* MY SIGN UP PAGE CODE*
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="sign_up.aspx.cs" Inherits="WebApplication4.sign_up" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Label ID="lblssignup" runat="server" BackColor="#FF99CC" Text="SIGN UP"></asp:Label>
<br />
<br />
<p>
<asp:Label ID="lblsuserid" runat="server" Text="ENTER USER ID"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" style="margin-bottom: 0px"></asp:TextBox>
</p>
<asp:Label ID="lblspassword" runat="server" Text="ENTER PASSWORD"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" Width="66px" />
</p>
</form>
</body>
</html>
SIGN UP PAGE BUTTON CODE FOR ENTERING DATA INTO SQL SERVER DATABASE ON BUTTON CLICK
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using middlelayer;
namespace WebApplication4
{
public partial class sign_up : System.Web.UI.Page
{
string conString = ConfigurationManager.ConnectionStrings["DBcon"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conString);
con.Open();
string ins= "Insert into [LOGINDETAILS](USERID, PASSWORD) VALUES ('" +TextBox1.Text+ "' , '" +TextBox2.Text+ "')";
SqlCommand com = new SqlCommand(ins,con);
DataSet du = new DataSet();
SqlDataAdapter sdi = new SqlDataAdapter(com);
sdi.Fill(du);
con.Close();
}
}
}
I AM getting error in this last code only of sign up button it is not able to insert values of SIGN UP webform Textbox to sql server databse table and also not reflecting the real values which I want to add in sql server TABLE using sign up webform and also noty saving it. It is sending some error values . kindly help me with this.
BELOW ARE THE IMAGES OF LOG IN AS WELL AS SIGN UP PAGE FOR REFERENCE
LOGIN PAGE WEB FORM
SIGN UP PAGE WEBFORM
KINDLY HELP IN RESOLVING THIS ISSUE
Try this:
SqlConnection con = new SqlConnection(conString);
con.Open();
string ins= "Insert into [LOGINDETAILS](USERID, PASSWORD) VALUES (#param1 , #param2)";
SqlCommand cmd = new SqlCommand(ins,con);
cmd.Parameters.Add("#param1", SqlDbType.Varchar, 50).value = TextBox1.Text;
cmd.Parameters.Add("#param2", SqlDbType.Varchar, 50).value = TextBox2.Text;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close()

asp.net web form button onclick event error

I have asp.net web form and when Im trying to assing onclick event to a button I get following error:
Compiler Error Message: CS1061: 'ASP.webform1_aspx' does not contain a definition for 'Button1_Click' and no extension method 'Button1_Click' accepting a first argument of type 'ASP.webform1_aspx' could be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 19: Line 20: Line 21:
Line 22:
Line 23:
ASP code is following:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!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 runat="server">
<title></title>
</head>
<body>
<form id="Form1" runat="server" method="post">
<div class="page">
<p>Persons</p>
<asp:Literal id="drpdwn" runat="server" />
<p>TransactionType</p>
<select id="sel" runat="server">
<option>bilance </option>
<option>liekākais parādnieks un aizdevējs</option>
<option>vidējais aizņēmuma lielums</option>
</select>
<asp:Button ID="Button1" runat="server" Text="Click Me" OnClick="Button1_Click" />
<table id="HTMLTable" width="300px;" runat="server">
<tr>
<td>
<b></b>
</td>
</tr>
</table>
</div>
</form>
</body>
<script type="text/javascript" >
var yourSelect = document.getElementById("sel");
var asdasd = yourSelect.options[yourSelect.selectedIndex].value;
</script>
</html>
And Codebehind is following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.UI.HtmlControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//int selectedIndex = (sel as HtmlSelect).SelectedIndex;
sel.Value.ToString();
SqlConnection cnn = new SqlConnection();
SqlDataReader rdr = null;
SqlCommand command = new SqlCommand();
cnn.ConnectionString = #"Server=localhost;Database=TildeTest;uid=AdminUser;pwd=AdminPwd;app=WebApplication1;";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string CommandText = "select * from persons";
command = new SqlCommand(CommandText);
command.CommandType = CommandType.Text;
//command.Connection = cnn;
try
{
cnn.Open();
command.Connection = cnn;
rdr = command.ExecuteReader();
if (rdr.HasRows)
{
drpdwn.Text = "<select>";
drpdwn.Text += "<option> </option>";
while (rdr.Read())
{
drpdwn.Text += "<option>" + rdr.GetString(1) + "</option>";
}
drpdwn.Text += "</select>";
}
else
{
Console.WriteLine("No rows found.");
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine(e.ToString());
}
finally
{
if (cnn.State == ConnectionState.Open)
cnn.Close();
}
}
void Button1_Click(Object sender,
EventArgs e)
{
// do something
}
}
}
you can change void Button1_Click to protected void Button1_Click and try.
Assuming you are using visual studio, double click the button from design view, then write the code behind inside the generated function. That should work.

How to add ASP.net and HTML Controls to the page at runtime?

I have an ASP.net WebForm. The markup is like:
<div>
<input type="text" id="input" runat="server" value=" " />
<asp:Button Text="send" OnClick="btnsend_Click" ID="btnsend" runat="server" />
</div>
This HTML is generated at runtime . The events are defined in the code behind file.
I need to add these controls at runtime. I tried to use the Literal-Control but the controls are working just like HTML Controls and not like ASP.net Controls.
EDIT:
Note: The Project type should be Website, not a web Application. Web application won't support on demand compilation where website yes, it is.
If I understood currectly, you want to take the Markup from User which contains even asp.net controls and scriplets too.
if this is the case, Follow below steps:
Create a dummy .ascx control file, like DynamicMarkup.ascx with empty content
Add this user control to the page (xxxx.aspx) where you want to show this control statically so it registered to the page
<%# Register src="~/DynamicMarkup.ascx"
tagname="DynamicMarkup" tagprefix="MyASP" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder runat="server"
ID="DynamicMarkupContainer" ></asp:PlaceHolder>
</div>
</form>
</body>
</html>
Write user input markup (may be get from database based on your criteria) to the DynamicMarkup.ascx file in page OnInit of the page (xxxx.aspx) And the create object of this DynamicMarkup
DynamicMarkup dynamicMarkup = LoadControl("~/DynamicMarkup.ascx") as
DynamicMarkup;
DynamicMarkupContainer.Controls.Add(ucSimpleControl);
I have not tested this approach, Just give a thought, With this you may get some session overwriting issue which you need handle.
Hope this will help!!
OLD:
is this the one that you are expecting? TextBox, and Button controls are available in System.Web.UI.WebControls namespace.
void Page_Load(Object sender, EventArgs e)
{
TextBox input = new TextBox();
input.Id ="input";
this.PlaceHolder.Controls.Add(input);
Button btnSend=new Button();
btnSend.Id ="btnSend";
btnSend.Text="Send";
btnSend.Click += new EventHandler(btnSend_Click);
this.PlaceHolder.Controls.Add(btnSend);
}
void btnSend_Click(object sender, EventArgs e)
{
// throw new NotImplementedException();
}
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:PlaceHolder ID="phHolder" runat="server"></asp:PlaceHolder>
</form>
</body>
</html>
code behind :
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Init()
{
GenerateContorls();
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void GenerateContorls()
{
TextBox newTxt = new TextBox() { ID = "txtsend" };
Button newBtn = new Button() { Text = "Send", ID = "btnsend" };
newBtn.Click += btnsend_Click;
phHolder.Controls.Add(newTxt);
phHolder.Controls.Add(newBtn);
}
protected void btnsend_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox)this.FindControl("txtsend");
//your code
}
}
hope it helps

Insert Data into SQL table using Javascript and ASP.NET

Im using Microsoft Visual Studio 2012 as platform and i have created Web Forms Project
i have created data base file "SimpleDB.mdf" inside his "Table" folder i added new table called "Table" which has two columns - id and Name(string).What im trying is to insert string data into Name column of this table while calling server side function from javascript function.
This is the aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Services;
namespace ProjectWWW
{
public partial class WebForm1 : System.Web.UI.Page
{
[WebMethod]
public static string InsertData(string ID){
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
{
SqlCommand cmd = new SqlCommand("Insert into Table(Name) values('" + ID + "')", con);
{
con.Open();
cmd.ExecuteNonQuery();
return "True";
}
}
}
}
and this is the aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ProjectWWW.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Error');
}
</script>
</head>
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
</html>
So basically im expecting when the button submit is clicked the Table Column "Name" will be filled with "Hello" but nothing happens and the column stays empty(NULL)
Table is reserved word in T-SQL so i would suggest you to use [] square brackets to enclose the Table.
Try This:
SqlCommand cmd = new SqlCommand("Insert into [Table](Name)
values('" + ID + "')", con);
Suggestion: Your query is open to sql injection attacks.I would suggest you to use Parameterised Queries to avoid them.
Try This:
using(SqlConnection con = new SqlConnection(source))
{
using(SqlCommand cmd = new SqlCommand("Insert into [Table](Name)
values(#Name)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Name",ID);
cmd.ExecuteNonQuery();
return "True";
}
}

C# User interface when uploading excel spreadsheet to SQL Database via VS 2005

currently I have a web which loads excel spreadsheet data into SQL database. When the page loads, all the parameters are hard coded on the code behind, so I do not have 'browse for file' and 'upload' button. I would like to implement these 2 buttons but I am not sure how should I do it.
I am using C# language, Visual Studio 2005 and SQL Server 2005.
Below is the code which runs the import of excel data into the database:
importexcel.aspx.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
public partial class ImportExcel : System.Web.UI.Page
{
public static string path = #"c:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\insqlserver\studentsheet1.xls";
public static string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
protected void Page_Load(object sender, EventArgs e)
{
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(connStr))
{
OleDbCommand command = new OleDbCommand
("Select StudentName,RollNo,Course FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<database>;User ID=<userid>;Password=<password>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "tStudent";
bulkCopy.WriteToServer(dr);
}
}
}
}
}
Below is my code for the my current html:
importexcel.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="ImportExcel.aspx.cs" Inherits="ImportExcel" %>
<!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">
<title></title>
<script language="javascript" type="text/javascript">
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
Please select a Excel spreadsheet to import:<br />
<asp:FileUpload ID="fupExcel" runat="server" />
<br />
<br />
<asp:Button ID="btnImport" runat="server"
Text="Import" onclick="btnImport_Click" />
<br />
<br />
<a href=http://localhost:1701/SoD>Click to go to main page</a>
</form>
</body>
</html>
I am not sure how do I attach the 2 buttons to my background code, someone teach me? Best if with sample code, thanks a lot!
First, the code in your page load needs to execute only if(IsPostBack) or on button click.
Second, (At leas modern) browsers won't let you change the value of the input file field, or click it.
You might try with some flash upload thing or so, but I don't expect much.

Categories

Resources