Full Email Address is not Showing in #Email Column - c#

I have a page for registration where i am saving details of users.
Page is working fine data is shaving but 'full email address' is not showing in table of '#email' column.
Example: if i am saving 'cozm02011#gmail.com' it is showing only 'cozm02011' in table.
code behind
protected void ceratenewuser_Click(object sender, EventArgs e)
{
String ConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "User_pro";
cmd.Parameters.AddWithValue("#UserName", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#Password", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("#Email", TextBox3.Text.Trim());
cmd.Parameters.AddWithValue("#LastSeen", DateTime.Now);
cmd.Parameters.AddWithValue("#CreatedDate", DateTime.Now);
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
Label2.Text = "User Created successfully";
TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; TextBox4 .Text = "";
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
this.GridView1.DataBind();
}
store procedure
ALTER PROCEDURE dbo.User_pro
#UserName varchar(20),
#Password varchar(20),
#Email varchar(50),
#LastSeen datetime,
#CreatedDate datetime
AS
INSERT INTO User_tbl (UserName, Password, Email, LastSeen, CreatedDate)
VALUES (#UserName, #Password, #Email, #LastSeen, #CreatedDate)
RETURN

You are binding the "Confirm password" field to the E-mail column
cmd.Parameters.AddWithValue("#Email", TextBox3.Text.Trim());
TextBox3 is used for "Confirm password" field.

Try this,
cmd.Parameters.AddWithValue("#Email", TextBox4.Text.Trim());

Related

Command object passing any values in asp.net web forms

I have a table with 1 record and I made a stored procedure for it to use in my button click, but it's letting me pass any values and when I test it in sql, it works as expected. Just wondering if any of you can point out the bug in my code.
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlDataReader dr = default(SqlDataReader);
SqlCommand cmd = default(SqlCommand);
string userName = txtUserName.Text;
string password = txtPassword.Text;
using (SqlConnection conn = new SqlConnection(strConn))
{
cmd = new SqlCommand("adminAuthentication", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Username", userName);
cmd.Parameters.AddWithValue("#Password", password);
conn.Open();
dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
lblMessage.Text = "Successfull login!";
}
else
{
lblMessage.Text = "Wrong user/password";
conn.Close();
}
}
}
Stored procedure:
CREATE PROC adminAuthentication
(
#UserName varchar(15),
#Password varchar(25)
)
AS
BEGIN
SELECT COUNT(1)
FROM AdminLogin
WHERE UserName = #UserName AND Pwd = #Password
END

ASP SQL How to check if username already exists in database table?

I am currently working with SQL database and my assignment is to make a registration form. I have got the registration form to work but I need to check if username have already been taken. In my code Username is in the form of Emails. The code I have works, but as it is, multiple usernames are allowed.
HEre is my code:
protected void registerUser(Object src, EventArgs e)
{
Response.Write("you have connected to your .cs page add records");
get_connection();
try
{
connection.Open();
command = new SqlCommand("INSERT INTO subscribers (FirstName, LastName, Email, Password)" +
" VALUES (#FirstName, #LastName, #Email, #Password)", connection);
command.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
command.Parameters.AddWithValue("#LastName", txtLastName.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#Password", txtPassword.Text);
command.ExecuteNonQuery();
//connection.Close();
}
catch(Exception err)
{
lblInfo.Text = "Error reading the database. ";
lblInfo.Text += err.Message;
}
finally
{
connection.Close();
lblInfo.Text += "<br /><b>Record has been added</b>";
//lblInfo.Text = "<b>Server Version:</b> " + connection.ServerVersion;
lblInfo.Text += "<br /><b>Connection Is:</b> " + connection.State.ToString();
}
}
To check if the username had already been taken, I was thinking about using an "If Then" statement within the "try" area but am unsure what coding I would need. Any help or advice would be appreciated.
You can write something like this:
string cmdText = #"IF NOT EXISTS(SELECT 1 FROM subscribers where Email = #Email)
INSERT INTO subscribers (FirstName, LastName, Email, Password)
VALUES (#FirstName, #LastName, #Email, #Password)"
command = new SqlCommand(cmdText, connection);
......
You can try this code :
string sqlQuery = "IF NOT EXISTS (SELECT 1 FROM subscribers where Email = #Email)
BEGIN
INSERT INTO subscribers (FirstName, LastName, Email, Password) VALUES (#FirstName, #LastName, #Email, #Password)
SELECT SCOPE_IDENTITY()
END
ELSE SELECT 0"
using (command = new SqlCommand())
{
command.CommandText = sqlQuery;
command.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
command.Parameters.AddWithValue("#LastName", txtLastName.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#Password", txtPassword.Text);
connection.Open();
var res = (int)cmd.ExecuteScalar();
connection.Close();
}
if a result is 0 then already exists otherwise new record inserted.

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.

Update statement doesn't update my data

I would like to update/edit my user data in Employee table in access database.
When i complete the fields that i want to change (name , last name, etc.), it gives me data updated but when i refresh the table, the data hasn't changed - been updated.
Changes i want to perform for example - Change name from Luke to Taylor, etc.
Where have i gone wrong? Where is the mistake in the code and does my code for adding users to database somehow have influence my update code?
My code for adding users is almost the same as for the update, except for query, and it works fine.
private void button2_Click(object sender, EventArgs e)
{
try
{
command.Connection = myConnection;
command.CommandText = "Update Employee set Name = #Name, LastName = #LastName, UserName = #UserName, Password = #Password, E_mail = #E_mail, Address = #Address WHERE ID = #ID";
command.Parameters.AddWithValue("#ID", userID.Text);
command.Parameters.AddWithValue("#Name", name.Text);
command.Parameters.AddWithValue("#LastName", lastName.Text);
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", pass.Text);
command.Parameters.AddWithValue("#E_mail", email.Text);
command.Parameters.AddWithValue("#Address", address.Text);
myConnection.Open();
command.ExecuteNonQuery();
MessageBox.Show("User updated!");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Code for adding user data
private void button1_Click(object sender, EventArgs e)
{
try
{
command.Connection = myConnection;
command.CommandText = "Insert into Employee (ID, Name, LastName, UserName, Password, E_mail, Address)" + "values (#ID, #Name, #LastName, #UserName, #Password, #E_mail, #Address)";
command.Parameters.AddWithValue("#ID", userID.Text);
command.Parameters.AddWithValue("#Name", name.Text);
command.Parameters.AddWithValue("#LastName", lastName.Text);
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", pass.Text);
command.Parameters.AddWithValue("#E_mail", email.Text);
command.Parameters.AddWithValue("#Address", address.Text);
myConnection.Open();
command.ExecuteNonQuery();
MessageBox.Show("User added!");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks for the replies and help
I still have no solution for this. I've tried so many things but i just don't get the right answer.
My current code
try
{
OleDbConnection myConnection = new OleDbConnection("\\DATABASE PATH");
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
cmd.CommandText = "UPDATE Employees SET Name = #Name, LastName = #LastName, UserName = #UserName, Password = #Password, E_mail = #E_mail, Address = #Address WHERE ID = #";
cmd.Parameters.AddWithValue("#ID", userID.Text);
cmd.Parameters.AddWithValue("#Name", name.Text);
cmd.Parameters.AddWithValue("#LastName", lastName.Text);
cmd.Parameters.AddWithValue("#UserName", userName.Text);
cmd.Parameters.AddWithValue("#Password", pass.Text);
cmd.Parameters.AddWithValue("#E_mail", eMail.Text);
cmd.Parameters.AddWithValue("#Address", address.Text);
myConnection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("User successfully added.");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Its because your ID in where condition.
You are also changing/updating your ID through:
command.Parameters.AddWithValue("#ID", userID.Text);
This new ID is not found by compiler in Database since you kept where ID=#ID condition in your query.
When you just updates name and other fields then query becomes:
Update Employee set Name = 'Name', LastName = 'LastName', UserName = 'UserName', Password = 'Password', E_mail = 'E_mail', Address = 'Address' WHERE ID = ''";
Your ID might remain blank in that case.
Try the following in your update code:
command.CommandText = "UPDATE Employee SET [Name] = ?, LastName = ?, UserName = ?, [Password] = ?, [E_mail] = ?, Address = ? WHERE [ID] = ?";
command.Parameters.AddWithValue("#Name", name.Text);
command.Parameters.AddWithValue("#LastName", lastName.Text);
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", pass.Text);
command.Parameters.AddWithValue("#E_mail", email.Text);
command.Parameters.AddWithValue("#Address", address.Text);
command.Parameters.AddWithValue("#ID", userID.Text);
The parameters must be in the order in which they appear in the CommandText. This answer was suggested by: Microsoft Access UPDATE command using C# OleDbConnection and Command NOT working
The reasons for this is outlined here: http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters(v=vs.110).aspx
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used.

SQL Server error: ExecuteNonQuery: Connection property has not been initialized

I am trying to develop a sample registration page using ASP.Net and C#. I am calling a stored procedure to insert the data to database. My database is SQL Server 2008.
This is my code:
public partial class Sample : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
string str;
protected void Page_Load(object sender, EventArgs e)
{
rbt_Male.Checked = true;
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
string #Name = txtbx_Name.Text;
string #Gender_male = rbt_Male.Text;
string #Gender_Female = rbt_Female.Text;
string #Email = txtbx_Email.Text;
DateTime #Dob = Convert.ToDateTime(txt_Dob.Text);
submitdata();
}
protected void submitdata()
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertdata";
if (rbt_Male.Checked)
{
cmd.Parameters.AddWithValue("#Name", txtbx_Name.Text);
cmd.Parameters.AddWithValue("#Gender_Male", rbt_Male.Text);
cmd.Parameters.AddWithValue("#Email", txtbx_Email.Text);
cmd.Parameters.AddWithValue("#Dob", Convert.ToDateTime(txt_Dob.Text));
}
else if (rbt_Female.Checked)
{
cmd.Parameters.AddWithValue("#Name", txtbx_Name.Text);
cmd.Parameters.AddWithValue("#Gender_Female", rbt_Male.Text);
cmd.Parameters.AddWithValue("#Email", txtbx_Email.Text);
cmd.Parameters.AddWithValue("#Dob", Convert.ToDateTime(txt_Dob.Text));
}
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
lbl_Errormsg.Visible = true;
lbl_Errormsg.Text = "Record Inserted Successfully";
con.Close();
}
catch (Exception ex)
{
lbl_Errormsg.Visible = true;
lbl_Errormsg.Text = ex.Message;
}
I am getting the error message
ExecuteNonQuery: Connection property has not been initialized.
I am getting this error at cmd.ExecuteNonQuery();
Please help me.
My stored procedure is
ALTER Procedure insertdata
(
#Name Varchar(20),
#Gender Varchar(6),
#Email Varchar(20),
#Dob date
)
As
Begin
Insert into samplelogintable (Name, Gender, Email, Dob)
Values(#Name, #Gender, #Email, #Dob)
End
You haven't associated your command cmd with your SqlConnection, that is why you are getting the error.
You need to specify:
cmd.Connection = con;
in your submitdata() method.
Since SqlCommand implements IDisposable, its better if you use it within using block like:
using (SqlCommand cmd = new SqlCommand())
{
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertdata";
cmd.Connection = con;
.... your code
}

Categories

Resources