EndExecuteNonQuery Error - c#

i have an error as which is on the button click event, as its shows me an error message on this line:
com.EndExecuteNonQuery();
message text: Error 2 No overload for method 'EndExecuteNonQuery' takes 0 arguments
Thank you for your support
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["usradmadslistview"].ConnectionString);
conn.Open();
string cmdStr = "Select count(*) from UserInfo where UID = '" + UsrNme.Text + "'";
SqlCommand com = new SqlCommand(cmdStr, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
chkusrnamlbl.Visible = true;
}
conn.Close();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["usradmadslistview"].ConnectionString);
conn.Open();
string insertquery = "insert into UserInfo (UID,FN,LN,Password,Email,CountID,State,City) Values (#username,#firstn,#lastn,#passbox,#email1,#country,#state,#city)";
SqlCommand com = new SqlCommand(insertquery, conn);
com.Parameters.AddWithValue("#username", UsrNme.Text);
com.Parameters.AddWithValue("#firstn", fnbox.Text);
com.Parameters.AddWithValue("#lastn", lnamebox.Text);
com.Parameters.AddWithValue("#passbox", passtxtbx1.Text);
com.Parameters.AddWithValue("#email1", emailbox.Text);
com.Parameters.AddWithValue("#country", DrDncoundrlst.SelectedItem.ToString());
com.Parameters.AddWithValue("#state", DropDownListSwestate.SelectedItem.ToString());
com.Parameters.AddWithValue("#city", citytxtbox.Text);
com.EndExecuteNonQuery();
Response.Redirect("User panel.aspx");
conn.Close();
}
catch(Exception ex) {
Response.Write("Error:" + ex.ToString());
}

EndExecuteNonQuery requires an IAsyncResult parameter as mentioned here in MSDN.
Also, is this just a code snippet? Because I think you would want to use com.ExecuteNonQuery() instead. EndExecuteNonQuery is the end pair for asynchronously executing SQL statements.

Related

The Update Statement is not working

protected void Button6_Click(object sender, EventArgs e)
{
Random rnd = new Random();
string resetpassword = rnd.Next(5000, 100000).ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString);
conn.Open();
string reset = "UPDATE Users SET" + " Password=#pass" + " WHERE UserName=#user";
SqlCommand com = new SqlCommand(reset, conn);
com.Parameters.AddWithValue("#pass", resetpassword);
com.Parameters.AddWithValue("#user", TextBox1.Text);
conn.Close();
}
For some reason, the password is not updated.
You forgot to execute the query:
int cnt = com.ExecuteNonQuery();
The method returns the number of affected rows.
Execute query
protected void Button6_Click(object sender, EventArgs e)
{
Random rnd = new Random();
string resetpassword = rnd.Next(5000, 100000).ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString);
conn.Open();
string reset = "UPDATE Users SET" + " Password=#pass" + " WHERE UserName=#user";
SqlCommand com = new SqlCommand(reset, conn);
com.Parameters.AddWithValue("#pass", resetpassword);
com.Parameters.AddWithValue("#user", TextBox1.Text);
com.ExecuteNonQuery();
conn.Close();
}

Username check is not working when user registers -asp.net

i want to check if the username already exists in the database and if yes, error message will prompt that says "username already exist". now i have this code but its not working. program still accepts the username even if it is duplicated from the database. can someone help me out pls? here is my whole registration code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
if (temp == 1) // check if user already exist.
{
Response.Write("User already existing");
}
conn.Close();
}
}
protected void btn_Registration_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
SqlCommand scm = new SqlCommand(insertQuery, conn);
scm.Parameters.AddWithValue("#Username", txtUser.Text);
scm.Parameters.AddWithValue("#Firstname", txtFN.Text);
scm.Parameters.AddWithValue("#Lastname", txtLN.Text);
scm.Parameters.AddWithValue("#Email", txtEmail.Text);
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
scm.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
scm.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
scm.Parameters.AddWithValue("#Zip", txtZip.Text);
scm.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
scm.ExecuteNonQuery();
Session["Contact"]= txtContact.Text;
Session["Email"] = txtEmail.Text;
Session["DeliveryAddress"] = txtAddress.Text;
label_register_success.Text = ("Registration Successful!");
//Response.Redirect("Home.aspx");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
You validate data on Page_Load? I think, you can choose to these solusions
You have to do it in btn_Registration_Click before you insert the
data, or
Maybe, you can modify it to do in sp and throw message through it if data is
duplicated and do the checking there.
It should be like this (according to solution 1)
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
}
}
protected void btn_Registration_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
if (temp > 0) // check if user already exist.
{
Response.Write("User already existing");
}
else
{
string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
scm = new SqlCommand(insertQuery, conn);
scm.Parameters.AddWithValue("#Username", txtUser.Text);
scm.Parameters.AddWithValue("#Firstname", txtFN.Text);
scm.Parameters.AddWithValue("#Lastname", txtLN.Text);
scm.Parameters.AddWithValue("#Email", txtEmail.Text);
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
scm.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
scm.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
scm.Parameters.AddWithValue("#Zip", txtZip.Text);
scm.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
scm.ExecuteNonQuery();
Session["Contact"]= txtContact.Text;
Session["Email"] = txtEmail.Text;
Session["DeliveryAddress"] = txtAddress.Text;
label_register_success.Text = ("Registration Successful!");
//Response.Redirect("Home.aspx");
}
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}

Error by this code

When I fill out the form and click registration, it shows an error:
Object reference not set to an instance of an object.
The error is here:
int temp=Convert.ToInt32(com.ExecuteScalar().ToString());
Which object must be added to refrence?
Here is the code of the web page:
public partial class register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
if(IsPostBack)
{
SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionS
tring"].ConnectionString);
conn.Open();
string checkuser = "SELECT * FROM [Table] where user_name ='" +
Text_username + "'";
SqlCommand com = new SqlCommand (checkuser , conn);
int temp=Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1){
Response.Write("User already exists");
}
conn.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Text_fname.Text = "";
Text_lname.Text = "";
Text_email.Text = "";
Text_password.Text = "";
Text_password_again.Text = "";
Text_username.Text = "";
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionS
tring"].ConnectionString);
conn.Open();
string insert = "insert into Table
(user_fname,user_lname,user_email,user_password,user_name) values (#firstName
,#lastName ,#Email ,#passWord ,#userName)";
SqlCommand com = new SqlCommand (insert , conn);
com.Parameters.AddWithValue("#firstName", Text_fname.Text);
com.Parameters.AddWithValue("#lastName", Text_lname.Text);
com.Parameters.AddWithValue("#Email", Text_email.Text);
com.Parameters.AddWithValue("#passWord", Text_password.Text);
com.Parameters.AddWithValue("#userName", Text_username.Text);
com.ExecuteNonQuery();
Response.Write("Registration is successful");
Response.Redirect("Default.aspx");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
}
}
From the error message you have posted, it is clear that the com.ExecuteScalar() is null. Hence, when you call the ToString method on it you get a null reference exception. Since the com.ExecuteScalar() can be null, I suggest you do a check for this.
int temp;
var result = com.ExecuteScalar();
if(result != null)
{
temp = Convert.ToInt32(result.ToString());
}
if (temp == 1)
{
Response.Write("User already exists");
}

Object reference not set to an instance of an object for asp.net

protected void Page_Load(object sender, EventArgs e)
{
lb_msg2.Text = "Hello " + Session["userid"].ToString() + "!";
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ProfileCS"].ConnectionString;
string sql = "Select password from Profile where userid = '" + Session["userid"] + "'";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr; // to hold reference of datareader returned
//prepare a place - datatable to hold the data
DataTable dt = new DataTable();
//setting up command
cmd.CommandText = sql;
cmd.Connection = con;
//connection and execute command
con.Open();
dr = cmd.ExecuteReader();
dt.Load(dr); // copy data from datareader to datatable
string pwdcheck;
pwdcheck = dt.Rows[0]["password"].ToString();
if (tb_verify.Text.Equals(pwdcheck))
{
string password = tb_pwd.Text;
sql = "Update Profile set password ='" + password + "'";
sql = sql + "where userid = '" + Session["userid"] + "'";
cmd.CommandText = sql;
cmd.Connection = con;
try
{
cmd.ExecuteNonQuery();
lb_msg.Text = "Password changed succesfully";
}
catch (Exception ex)
{
lb_msg.Text = "Problems encountered " + ex.Message;
}
finally
{
con.Close();
con.Dispose();
cmd.Dispose();
}
}
else
lb_msg.Text = "Old password Incorrect";
}
protected void lblClick(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Session.Clear(); // This may not be needed -- but can't hurt
Session.Abandon();
FormsAuthentication.RedirectToLoginPage();
}
}
lb_msg2.Text = "Hello " + Session["userid"].ToString() + "!";
there is an error at the line above with
Object reference not set to an instance of an object the change password feature was working before.
In your case Session["userid"] must be NULL,handle it

SQL Insert Query Using C#

I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#
The things I tried (worked)
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
A new line was inserted and everything worked fine, now I tried to insert a row using variables:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id, #username, #password, #email)";
command.Parameters.AddWithValue("#id","abc")
command.Parameters.AddWithValue("#username","abc")
command.Parameters.AddWithValue("#password","abc")
command.Parameters.AddWithValue("#email","abc")
command.ExecuteNonQuery();
Didn't work, no values were inserted. I tried one more thing
command.Parameters.AddWithValue("#id", SqlDbType.NChar);
command.Parameters["#id"].Value = "abc";
command.Parameters.AddWithValue("#username", SqlDbType.NChar);
command.Parameters["#username"].Value = "abc";
command.Parameters.AddWithValue("#password", SqlDbType.NChar);
command.Parameters["#password"].Value = "abc";
command.Parameters.AddWithValue("#email", SqlDbType.NChar);
command.Parameters["#email"].Value = "abc";
command.ExecuteNonQuery();
May anyone tell me what I am doing wrong?
Kind regards
EDIT:
in one other line I was creating a new SQL-Command
var cmd = new SqlCommand(query, connection);
Still not working and I can't find anything wrong in the code above.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id","abc");
command.Parameters.Add("#username","abc");
command.Parameters.Add("#password","abc");
command.Parameters.Add("#email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#id", "abc");
command.Parameters.AddWithValue("#username", "abc");
command.Parameters.AddWithValue("#password", "abc");
command.Parameters.AddWithValue("#email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Try
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username, #password, #email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("#id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("#password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
}
The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.
If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (#txtitemid,#txtitemname,#txtitemdesc,#txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("#txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("#txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("#txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("#txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;Password=P#ssw0rd";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
Console.WriteLine(" Connection Opened ");
command = new SqlCommand(sql, connection);
SqlDataReader dr1 = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
}

Categories