The name 'TextBox1' does not exist in the current context(usually) - c#

I am currently developing a website by visual studio c# language and right now I am working on the user password reset page design. The problem I met is that I want to add the control to the textboxes and labels by using basic textbox.text = ""; method. But it keeps telling me it did not exist. I have searched a lot of solutions I am sure that:
1, It is the same name between the label name and the coding name.
2, There were no other same name pages since I was re-created another page with different names.
3, All these are added:
using System;
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;
using System.Drawing;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.IO;
Can anyone help? I confused here for a few days already:)
protected void SubmitButton_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spResetPassword", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramUsername = new SqlParameter("#UserName", userTextBox.text);
cmd.Parameters.Add(paramUsername);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (Convert.ToBoolean(rdr["ReaturnCode"]))
{
SendPasswordResetEmail(rdr["Email"].ToString(), TextBox1.Text, rdr["UniqueId"].ToString());
msgLabel.Text = "An reset password Email has sent to your Email address.";
}
else
{
msgLabel.Text = "username not found!";
}
}
}

Does your textbox control have the following attribute?
runat="server"

Related

SQL Server exception 'Must declare the scalar variable "#nameQuery".'

I am creating a practice SQL Server database project, and I'm trying to enter text into a SQL Server database through a Windows Form. I'm not sure if my text data was really entered to my database. How do I view if it was entered? I'm a beginner so please try to use beginner SQL and VS vocabulary. I've tried going to show table data but that shows that no data was entered so I'm assuming its not working. Whenever I hit the button it just gives me no response so I'm not sure.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace DBHotel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Nicholas Hoffs\\source\\repos\\DBHotel\\DBHotel\\Hotel.mdf;Integrated Security=True";
private void instBttn_Click(object sender, EventArgs e)
{
string nameQuery = textInst.Text;
using(SqlConnection conn = new SqlConnection(connectionString))
{
using(SqlCommand cmd = new SqlCommand(nameQuery, conn))
{
conn.Open();
cmd.CommandText = "INSERT INTO Customers(name) VALUES(#nameQuery)";
cmd.Parameters.AddWithValue("nameQuery", nameQuery);
cmd.ExecuteNonQuery();
}
}
}
}
}
Help is very much appreciated, thanks!
I know this is nonintuitive but try using the # inside your AddWithValue:
cmd.Parameters.AddWithValue("#nameQuery", nameQuery);
EDIT: WARNING The below solution is at risk of sql injection, and is highly discouraged.
As you are using direct query in instead of using stored procedure, you can't pass parameter to SQL. Instead of passing parameter try using
cmd.CommandText = "INSERT INTO Customers(name) VALUES('" + nameQuery + "')";
this means we are just concatenating the value of variable "nameQuery" in the query itself. so no need of below statement
cmd.Parameters.AddWithValue("nameQuery", nameQuery);

Is this the correct way for connecting database (.mdf file) to visual studio project?

for this i am not getting any output thought there is not any error or warning... i guess the problem is with connection string but not sure, is it?? i have created a database name RV(.mdf file) in SQL server data tool and connected it to this project in visual studio.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Configuration;
namespace student_TableConnectTry1
{
class Program
{
static void Main(string[] args)
{
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString =#"Data Source=(local);Integrated Security=SSPI;" +"Initial Catalog=RV";
cn.Open();
string strSQL = "Select * From student";
SqlCommand myCommand = new SqlCommand(strSQL, cn);
using (SqlDataReader myDataReader = myCommand.ExecuteReader())
{
// Loop over the results.
while (myDataReader.Read())
{
Console.WriteLine("-> usn: {0}, name: {1}.",
myDataReader["usn"].ToString(),
myDataReader["name"].ToString()
);
}
}
Console.ReadLine();
}
}
}
}
You can use following connection string and try:
Integrated Security=SSPI;Persist Security Info=False;User ID=youruserid;Initial Catalog=databasename;Data Source=.\SQLEXPRESS
Also see the following link for connectionstring:
http://www.connectionstrings.com/sql-server/
I hope it will help you. :)
Let me know if it does not help you.

C# connection issue

My first issue: I am trying to establish connection to MySql database, but I keep getting error when I debug it with Visual Studio:"Connection must be valid and open."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=localhost;User Id=root;database=test3";
using (conn = new MySqlConnection(myConnectionString))
{
DateTime startTime = DateTime.Now;
MySqlCommand cmd = new MySqlCommand("SELECT * FROM department");
// sleep for 2.5s
Thread.Sleep(2500);
conn.Open();
var reader = cmd.ExecuteReader();
conn.Close();
}
}
}
My second issue: if there a way to display all this on a ASP.NET Web form (I want to leave code on server side), but display data something like ListView or GridView? Thanks in advance
You need to call conn.Open() before using it.
You forgot to attach your connection to the command:
cmd.Connection = conn;

Update DB using stored procedure and ADO.NET

I think I'm missing an 'USING" statement in my class as I'm getting an error when I try to set the commandType to stored procedure. When I type 'cmd.CommandType =', Intellisense fails to find the 'CommandType.StoredProcedure (Note: the function is only partly roughed out). Thanks in advance!
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;
namespace LegacyForms.Personal
{
public partial class FormBuilder : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Get the DB connection:
string ConnString = ConfigurationManager.AppSettings["AssociatedBank2011ConnectionString"];
SqlConnection conn = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand("uspInsertPersonalAccountApplcation", conn);
cmd.Commandtype = **get error here!**
cmd.Parameters.AddWithValue("#AccountType", AcctType);
cmd.Parameters.AddWithValue("#AccountSubType", AcctSubType);
cmd.Parameters.AddWithValue("#CheckingOption", CheckOption);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
using System.Data;
You need to reference System.Data. See the MSDN Reference for the CommandType Enumeration. Direct quote:
Namespace: System.Data
Assembly: System.Data (in System.Data.dll)
I'd also recommend the other using statement for your SqlConnection and SqlCommand objects. Since they both implement the IDisposable interface, you can do the following:
string ConnString = ConfigurationManager.AppSettings["AssociatedBank2011ConnectionString"];
using (SqlConnection conn = new SqlConnection(ConnString))
using (SqlCommand cmd = new SqlCommand("uspInsertPersonalAccountApplcation", conn))
{
cmd.Commandtype = CommandType.StoreProcedure;
cmd.Parameters.AddWithValue("#AccountType", AcctType);
cmd.Parameters.AddWithValue("#AccountSubType", AcctSubType);
cmd.Parameters.AddWithValue("#CheckingOption", CheckOption);
conn.Open();
cmd.ExecuteNonQuery();
}
That way, in the case that your code works correctly or throws an exception in the using block, your SqlConnection and SqlCommand will clean up after themselves.
In such situations you can press CTRL + . (ctrl + dot) to get a suggestion like do you want to add using System.Data...
P.S. Teach a men to fish ...

AS400 C#.net inserting new record problems

I am trying to build a C#.net program that works like a RPG Subfile on the AS400.
Have the general subfile part working. I can display and then edit and update existing records.
Am blowing up in my code where I am trying to insert a new record. Blowing up on the
cmd.ExecuteNonQuery();
If you want to see how this works without the insert go to
http://144.162.90.78/thomas/
Look at the Website1a
Here is the code.
using IBM.Data.DB2.iSeries;
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class WebForm3 : System.Web.UI.Page
{
protected void btnBack_Click(object sender, EventArgs e)
{
Server.Transfer("WebForm1a.aspx");
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
ConnectionStringSettingsCollection cssc =
ConfigurationManager.ConnectionStrings;
String connString = cssc["FTWAS400"].ToString();
iDB2Connection conn = new iDB2Connection(connString);
conn.Open();
iDB2Command cmd = new iDB2Command(
"insert into tburrows.qcustcdt (cusnum, init, lstnam, street, city, state, zipcod, cdtlmt, chgcod, baldue, cdtdue) values (#cusnum, #init, #lstnam, #street, #city, #state, #zipcod, #cdtlmt, #chgcod, #baldue, #cdtdue)", conn);
cmd.DeriveParameters();
cmd.Parameters["#cusnum"].Value = Request["txtCUSNUM"];
cmd.Parameters["#init" ].Value = Request["txtINIT"];
cmd.Parameters["#lstnam"].Value = Request["txtLSTNAM"];
cmd.Parameters["#street"].Value = Request["txtSTREET"];
cmd.Parameters["#city"].Value = Request["txtCITY"];
cmd.Parameters["#state"].Value = Request["txtSTATE"];
cmd.Parameters["#zipcod"].Value = Request["txtZIPCOD"];
cmd.Parameters["#cdtlmt"].Value = Request["txtCDTLMT"];
cmd.Parameters["#chgcod"].Value = Request["txtCHGCOD"];
cmd.Parameters["#baldue"].Value = Request["txtBALDUE"];
cmd.Parameters["#cdtdue"].Value = Request["txtCDTDUE"];
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
btnBack_Click(sender, e);
}
}
Any help will greatly be appreciated.
Thomas
There is another option within the
cmd.Parameters["#cusnum"].Value = field;
to specify the field type. Use
cmd.Parameters.Add("#cusnum", iDB2DbType.iDB2Decimal).Value = Convert.ToDecimal(field);
instead. This should convert your data types properly. You will need to change the iDB2Decimal to the proper field type if not decimal.

Categories