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

I am facing several errors in my code. These errors are:
Error 17 The name 'CommandType' does not exist in the current context
Error 18 The name 'SqlDbType' does not exist in the current context
Error 35 The name 'txtCity' does not exist in the current context
I would like if you can help me to understand the error and tell me how I can fix it.
protected void btnSave_Click(object sender, EventArgs e)
{
// create connectionstring and insert statment
string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string insertSql = " INSERT INTO UserInfo (UID, FN, LN, Password, RePass, Email, Country,State, City)" +
" values (#UsrNme, #fnbox, #lnamebox, #passtxtbx1, #passtxtbx2, #emailbox, #DrDncoundrlst, #DropDownListSwestate, #citytxtbox)";
// create SQL Connection
SqlConnection con = new SqlConnection(connectionString);
// create sql command and parameters
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.text;
cmd.CommandText = insertSql;
SqlParameter UID = new SqlParameter("#UsrNme", SqlDbType.nvarchar, 50);
UID.Value = txtUID.text.tostring();
cmd.Parameters.Add(UID);
SqlParameter FN = new SqlParameter("#fnbox", SqlDbType.varchar,25);
cmd.Connection = con;
FN.Value = txtfn.text.ToString();
cmd.Parameters.Add(FN);
SqlParameter LN = new SqlParameter("#lnamebox", SqlDbType.varchar, 25);
cmd.Connection = con;
LN.Value = txtLN.text.ToString();
cmd.Parameters.Add(LN);
SqlParameter Password = new SqlParameter("#passtxtbx1", SqlDbType.varchar, 25);
cmd.Connection = con;
Password.Value = txtPassword.text.ToString();
cmd.Parameters.Add(Password);
SqlParameter RePass = new SqlParameter("#passtxtbx2", SqlDbType.varchar, 25);
cmd.Connection = con;
RePass.Value = txtRePass.text.ToString();
cmd.Parameters.Add(RePass);
SqlParameter Email = new SqlParameter("#emailbox", SqlDbType.varchar, 25);
cmd.Connection = con;
Email.Value = txtEmail.text.ToString();
cmd.Parameters.Add(Email);
SqlParameter Country = new SqlParameter("#DrDncoundrlst", SqlDbType.varchar, 25);
cmd.Connection = con;
Country.Value = txtCountry.text.ToString();
cmd.Parameters.Add(Country);
SqlParameter State = new SqlParameter("#DropDownListSwestate", SqlDbType.varchar, 25);
cmd.Connection = con;
State.Value = txtState.text.ToString();
cmd.Parameters.Add(State);
SqlParameter City = new SqlParameter("#citytxtbox", SqlDbType.varchar, 25);
cmd.Connection = con;
City.Value = txtCity.text.ToString();
cmd.Parameters.Add(City);
try
{
con.Open();
cmd.ExecuteNonQuery();
lblmsg.Text = "You already complete your registration process";
}
catch (SqlException ex)
{
string errorMessage = "error in registration user";
errorMessage += ex.Message;
throw new Exception(errorMessage);
}
finally
{
con.Close();
}
}

You may be way over-complicating things. Try the following code...
var connection = new SqlConnection(connectionString);
var cmd = new SqlCommand(insertSql, connection);
cmd.Parameters.AddWithValue("#UsrNme", txtUID.Text.ToString());
cmd.Parameters.AddWithValue("#fnbox", txtfn.Text.ToString());
cmd.Parameters.AddWithValue("#lnamebox", txtLN.Text.ToString());
cmd.Parameters.AddWithValue("#passtxtbx1", txtPassword.Text.ToString());
cmd.Parameters.AddWithValue("#passtxtbx1", txtPassword.Text.ToString());
cmd.Parameters.AddWithValue("#passtxtbx2", txtRePass.Text.ToString());
cmd.Parameters.AddWithValue("#emailbox", txtEmail.Text.ToString());
cmd.Parameters.AddWithValue("#DrDncoundrlst", txtCountry.Text.ToString());
cmd.Parameters.AddWithValue("#DropDownListSwestate", txtState.Text.ToString());
cmd.Parameters.AddWithValue("#citytxtbox", txtCity.Text.ToString());
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
lblmsg.Text = "You already completed your registration process";
}
catch (SqlException ex)
{
var errorMessage = "error in registration user";
errorMessage += ex.Message;
throw new Exception(errorMessage);
}
finally
{
con.Close();
}
You also want to make sure the you have the following using clauses declared...
using System.Data;
using System.Data.SqlClient;
... and that txtCity is what you actually called your text box and that it's not hidden from this method by a private identifier or actually appears on a different form because the error you're getting means that the variable is outside the method's scope or has its lifetime expire before you reach this method.
Here's what all that code does. Instead of setting up tons of metadata that you should not need to declare your parameters, it lets SqlCommand do all the hard work for you and figure out what type is what based on the database column, the type of the object you passed in, and the name of the parameter. If you end up allowing the passing of invalid data, none of the elaborate metadata markup is going to save you from an error.
Likewise, you really want to look into wrapping your insertSql into a stored procedure like so in Sql Server...
create procedure adduserinfo #UsrNme nvarchar (50),
#fnbox varchar (25),
#lnamebox varchar (25),
#passtxtbx1 varchar (25),
#passtxtbx2 varchar (25),
#emailbox varchar (25),
#DrDncoundrlst varchar (25),
#DropDownListSwestate varchar (25),
#citytxtbox varchar (25)
as begin
INSERT INTO UserInfo
( UID,
FN,
LN,
Password,
RePass,
Email,
Country,
State,
City )
VALUES
( #UsrNme,
#fnbox,
#lnamebox,
#passtxtbx1,
#passtxtbx2,
#emailbox,
#DrDncoundrlst,
#DropDownListSwestate,
#citytxtbox )
end
go
Then your SqlCommand declaration would look like so...
var command = new SqlCommand("adduserinfo", connection)
{
CommandType = CommandType.StoredProcedure;
}
... and for the rest you'd follow the rest of the code I provided above. This would be the more or less proper way to do it. And at the risk of sounding nitpicky, consider more informative and consistently formatted variable and parameter names. Those who might have to modify your code in the future will thank you for it.

Related

fatal error encountered during command execution in c#.net mysql

I have tried the code below when I am going to click Save button I got the error of "fatal error encountered during command execution" I rechecked more than two times but unfortunately error not go away. please, anyone kindly fix this error.
private void button1_Click(object sender, EventArgs e)
{
string cid, lname, fname,street,city,state,phone,date,email,aco,actype,des,bal;
cid = label14.Text;
lname = textBox1.Text;
fname = textBox2.Text;
street = textBox3.Text;
city = textBox4.Text;
state = textBox5.Text;
phone = textBox6.Text;
date = dateTimePicker1.Text;
email = textBox8.Text;
aco = textBox7.Text;
actype = comboBox1.Text;
des = textBox10.Text;
bal = textBox11.Text;
con.Open();
MySqlCommand cmd = con.CreateCommand();
MySqlTransaction transaction;
transaction = con.BeginTransaction();
StringBuilder cmdText = new StringBuilder();
cmdText.AppendLine("INSERT into customer (custid,lastname,firstname,street,city,state,phone,date,email) VALUES (#custid,#lastname,#firstname,#street,#city,#state,#phone,#date,#email)");
cmdText.AppendLine("INSERT into account(accid,custid,acctype,description,balance) VALUES (#accid,#custoid,#acctype,#description,#balance)");
cmd.CommandText = cmdText.ToString();
cmd.Connection = con;
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("#custid", cid);
cmd.Parameters.AddWithValue("#lastname", lname);
cmd.Parameters.AddWithValue("#firstname", fname);
cmd.Parameters.AddWithValue("#street", street);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#accid", aco);
cmd.Parameters.AddWithValue("#cusotid", cid);
cmd.Parameters.AddWithValue("#acctype", actype);
cmd.Parameters.AddWithValue("#description", des);
cmd.Parameters.AddWithValue("#balance", bal);
try
{
cmd.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Transaction Suceess");
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I have seen many developers encountering errors with their SQL because they are using AddWithValue on their SqlCommand. The issue with this is that the command doesn't know the data type of your sql command parameter.
You should use SqlParameterCollection.Add Method (String, SqlDbType, Int32) to specify the data type of the parameter. Refer to SqlDbType Enumeration for the SqlDbType enumeration.
Usage:
cmd.Parameters.Add("#custid", SqlDbType.Int).Value = cid;
cmd.Parameters.Add("#lastname", SqlDbType.Text).Value = lname;
P.S. I am assuming that there are no issues with your SQL connection string.

Input on a stored sql procedure using C#

In sql I normally execute my procedure using
exec dbo.usp_FCS 'TIMV','serial'
And I tried something somewhat the same in c# but it seems I got this wrong
using (SqlConnection connection = new SqlConnection("Data Source=;Initial Catalog=;User ID=;Password="))
{
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" + "'" + MachineName + " ','serial' " , connection))
{
try
{
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
}
catch (SqlException ex)
{
label6.Visible = true;
label6.Text = string.Format("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
}
}
My question is,how can I give those 2 inputs 'TIMV' and 'serial' of my stored procedure using c#?
Edit:
I tried something like this:
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" , connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#p2", SqlDbType.VarChar).Value = "serial";
try
{ my code...
And it is still not working
The most correct way to add a parameter to an SqlCommand is through the Add method that allows you to specify the datatype of the parameter and, in case of strings and decimals, the size and the precision of these values. In that way the Database Engine Optimizer can store your query for reuse and be a lot faster the second time you call it. In your case I would write
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 20).Value = MachineName;
cmd.Parameters.Add("#serial", SqlDbType.NVarChar, 20).Value = "serial";
This assumes that your stored procedure receives two parameters named EXACTLY #mname and #serial, the type of the parameters is NVarChar and the length expected is 20 char. To give a more precise answer we need to see at least the first lines of the sp.
In your code above also the execution of the command is missing. Just creating the command does nothing until you execute it. Given the presence of an SqlDataAdapter I think you want to fill a DataSet or a DataTable and use this object as DataSource of your grid. Something like this
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
yourDataGrid.DataSource = dt;
And if this is an ASP.NET app, also the DataBind call
yourDataGrid.DataBind();
You use the Parameters collection of the SqlCommand class to send parameters to a stored procedure.
Suppose your parameter names are #p1 and #p2 (Please, for your sake, don't use names like this ever) - your c# code would look like this:
using (var cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya", connection))
{
cmd..CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#21", SqlDbType.VarChar).Value = "serial";
try
{
// rest of your code goes here....
Note: use the SqlDbType value that fits the parameters data type.
Try this:
DataSet ds = new DataSet("dts");
using (SqlConnection conn = new SqlConnection
("Data Source=;Initial Catalog=;User ID=;Password="))
{
try
{
SqlCommand sqlComm = new SqlCommand("usp_FCS_GetUnitInfo_Takaya",conn);
sqlComm.Parameters.AddWithValue("#p1", MachineName);
sqlComm.Parameters.AddWithValue("#p2", "serial");
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
catch (Exception e)
{
label6.Visible = true;
label6.Text = string.Format
("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}

Sequential stored procedure with User Input

I have a web app that takes user input and generates an image from user input. Those images should be generated in a sequence and will need to reset everyday.
I'm trying to at least store the sequence values, the sequence and the date into a database, but it will not update.
So far, my database will not update, my code works, but is not performing correctly. I'm not sure where my problem lies. I found similar help online, but they did not seem to work.
Stored procedure:
ALTER PROCEDURE barcode_insert(
#Seq_Num int,
#date datetime,
#ImageName varchar
)
AS
BEGIN
SET NOCOUNT ON
UPDATE ImageInfoTable
SET imagedate = #date,ImageNum = #Seq_Num
WHERE image_name = #ImageName
END
RETURN #Seq_Num
C# Code
protected void gen_barcode(object sender, EventArgs e)
{
int n;
int i = Int32.Parse(amount.Text);
string date_picker = datepicker.Text;
SqlConnection conn = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "barcode_insert"
cmd.Parameters.AddWithValue("#Seq_Num", amount.Text);
cmd.Parameters.AddWithValue("#date", date_picker);
cmd.Parameters.AddWithValue("#ImageName", CheckBox.Checked);
if (CheckBox_Code.Checked)
{
//generate image code
}
cmd.Connection.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Try setting the types of your parameters explicitly.
protected void gen_barcode(object sender, EventArgs e)
{
DateTime date_picker = datepicker.Value;
int intAmount; // get the int value for the amount here...
String imgName; // get the image name here...
SqlConnection conn = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "barcode_insert"
cmd.Parameters.Add("#Seq_Num", SqlDbType.Int);
cmd.Parameters.Add("#date", SqlDbType.DateTime);
cmd.Parameters.Add("#ImageName" , SqlDbType.NVarChar);
cmd.Parameters["#Seq_Num"].Value = intAmount;
cmd.Parameters["#date"].Value = date_picker;
cmd.Parameters["#ImageName"].Value = imgName;
if (CheckBox_Code.Checked)
{
//put this somewhere else since it isn't related in function
}
cmd.Connection.Open();
cmd.ExecuteNonQuery();
conn.Close();
}

Stored procedure is not working and getting stopped

I m running a piece of code for scheduler in my project. But it is not working as expected.
private void Initiate_User(string strEmpCard)
{
//conn.Open();
ObjPriCmd = new SqlCommand("exec [sp_c_Initiate_Clearance] " + strEmpCard.ToString() + "", conn);
ObjPriCmd.ExecuteNonQuery();
}
The debugger stops and opens a form after my ExecuteNonQuery() line is debugged. I am not able to trace the error also. what is wrong here ??
UPDATE
My error query
insert into p_emp_clearance_hdr
(Emp_mkey,
Emp_card_no,
RA_1,
RA_2,
Depatment,
Sub_Department,
Date_of_Joining,
Resignation_date,
Last_Working_Days,
UserId)
select
em.mkey,
em.emp_card_no,
em.Reporting_To,
em.Reporting_To2,
em.Department_mkey,
em.SubDept_mkey,
convert(varchar(10), em.resig_date, 103) resig_date,
convert( varchar(10), em.Dt_Of_Join, 103) Dt_Of_Join,
convert(varchar(10), em.Dt_of_leave, 103) Dt_of_leave,
um.mkey
from emp_mst em join user_mst um
on em.mkey = um.Employee_mkey
where em.mkey = #emp_mkey
As you explained in comments, you are getting error:
ExecuteNonQuery: Connection property has not been initialized.
It means you have not initialized the connection. You have just declared it:
SqlConnection conn;
You should do like:
conn = new SqlConnection(#"you connection string");
//then your code
ObjPriCmd = new SqlCommand("exec [sp_c_Initiate_Clearance] " + strEmpCard.ToString(), conn);
ObjPriCmd.ExecuteNonQuery();
The best practice:
You should use a SqlCommand property CommandType to define that you're calling a StoredProcedure when calling from C#. And define parameters using SqlCommand .Parameters.Add it handles the SqlInjection issues itself.
conn = new SqlConnection(#"you connection string");
using (SqlCommand cmd = new SqlCommand("sp_c_Initiate_Clearance", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// parameter name , parameter type parameter value
cmd.Parameters.Add("#parameter name", SqlDbType.VarChar).Value = strEmpCard.ToString();
con.Open();
cmd.ExecuteNonQuery();
}
You can Try it with USing Statement:-
using (SqlCommand cmd = new SqlCommand("sp_c_Initiate_Clearance", conn)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Parameter Name", Type).Value = "Value of Parameter";
conn.Open();
cmd.ExecuteNonQuery();
}

ExecutenonQuery not working

I have stored proc as below:
ALTER PROC pr_Update_Users_Nomination
(
#UserID AS VARCHAR(100),
#Nominated AS BIT
)
AS
UPDATE User
SET isNominated = #Nominated
WHERE
EMPID = #UserID;
I want to call this procedure from c# code: Below is the code I am trying:
void OpenConnection()
{
string Nominated = "False";
//Connection String
string sConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString;
SqlConnection mySqlCon = new SqlConnection(sConnString);
SqlCommand mySqlCom = mySqlCon.CreateCommand();
//Call the stored proc and provide in parameters
mySqlCom.CommandText = "EXECUTE pr_Update #UserID #Nominated";
mySqlCom.Parameters.Add("#UserID", SqlDbType.VarChar, 20).Value = UserID;
mySqlCom.Parameters.Add("#Nominated", SqlDbType.Bit).Value = Nominated;
mySqlCon.Open();
mySqlCom.ExecuteNonQuery();
mySqlCon.Close();
}
I get an error saying
Incorrect Syntax near #Nominated
first, when executing a procedure with parameter(s), separate the parameters with a comma
EXECUTE pr_Update #UserID, #Nominated
second, modify your code into this,
string sConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString;
using(SqlConnection mySqlCon = new SqlConnection(sConnString))
{
using(SqlCommand mySqlCom = new SqlCommand())
{
mySqlCom.Connection = mySqlCon;
mySqlCom.CommandText = "pr_Update";
mySqlCom.CommandType = CommandType.StoredProcedure;
mySqlCom.Parameters.Add("#UserID", SqlDbType.VarChar, 20).Value = UserID;
mySqlCom.Parameters.Add("#Nominated", SqlDbType.Bit).Value = Nominated;
try
{
mySqlCon.Open();
mySqlCom.ExecuteNonQuery();
}
catch(SqlException ex)
{
// do something with the exception
// don't hide it
}
}
}
You are missing a comma (,) between the parameters.
It should be
mySqlCom.CommandText = "EXECUTE pr_Update #UserID, #Nominated";
mySqlCom.Parameters.Add("#UserID", SqlDbType.VarChar, 20).Value = UserID;
mySqlCom.Parameters.Add("#Nominated", SqlDbType.Bit).Value = Nominated;
Alternatively, since all you are doing is calling a stored proc, you could do:
mySqlCom.CommandType = CommandType.StoredProcedure ;
mySqlCom.CommandText = "pr_Update"; //no need to specify parameter names
mySqlCom.Parameters.Add("#UserID", SqlDbType.VarChar, 20).Value = UserID;
mySqlCom.Parameters.Add("#Nominated", SqlDbType.Bit).Value = Nominated;
Give only name of stored procedure, as you are adding parameter in statements after this. Also set CommandType.
mySqlCom.CommandText = "pr_Update";
mySqlCom.CommandType = CommandType.StoredProcedure;
You are invoking wrong SQL. You should set the command text of command to pr_Update only:
mySqlCom.CommandText = "pr_Update";
And set type command type to stored procedure:
mySqlCom.CommandType = CommandType.StoredProcedure;
See MSDN page for more.

Categories

Resources