I got a question. When I put this code
protected void Page_Load(object sender, EventArgs e)
{
string email = Membership.GetUser(User.Identity.Name).Email;
MembershipUser currentUser = Membership.GetUser();
string UserId = currentUser.ProviderUserKey.ToString();
**TextBox2.Text = email;
TextBox3.Text = UserId;**
}
My data will not be saved to the database.
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_Membership SET Email = #email WHERE UserId = #id1", conn);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
cmd.Parameters.AddWithValue("#id1", TextBox3.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
But when I removed
**TextBox2.Text = email;
TextBox3.Text = UserId;**
The data will be saved into database using above code. Can someone tell me why? Thanks in advance.
Given you never execute the command I can't explain it.
Add
cmd.ExecuteNonQuery();
To the end of your click method
Because you are setting the values in your page load event, they are overwriting the changed values in the controls when your button on postback. Wrap your page load code with a
if (!Page.IsPostback)
{
string email = Membership.GetUser(User.Identity.Name).Email;
MembershipUser currentUser = Membership.GetUser();
string UserId = currentUser.ProviderUserKey.ToString();
TextBox2.Text = email;
TextBox3.Text = UserId;
}
You are never executing your SQL so I'm very surprised that your DB is updating at all.
Take a look at the ExecuteNonQuery method. With your current query you are creating a SQLCommand and then never running the SQL.
Try the following
cmd.Connection = conn;
cmd.Connection.Open()
after you assign it and then
cmd.ExecuteNonQuery();
Related
I'm new to c# and currently I have some problems when I'm running this program without debugging.
This is the login page for my project. I've create a service-based database and I want to connect to the data which is username and password in the table 'Table' which is in the database.
However, I've encountered an issue which is "ExecuteScalar: Connection property has not been initialized." when I'm running this code.
Can anyone help me with this?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\hp\documents\visual studio 2015\Projects\PersonalFinancialSoftware\PersonalFinancialSoftware\Login.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT COUNT (*) FROM Table where UserID = #userid AND Password = #password";
cmd.Parameters.AddWithValue("#userid", textBox1.Text);
cmd.Parameters.AddWithValue("#password", textBox2.Text);
object result = cmd.ExecuteScalar();
conn.Open();
string useridlogin = Convert.ToString(result);
conn.Close();
if (useridlogin != " ")
{
Home_Page homepage = new Home_Page();
homepage.Show();
}
else
{
MessageBox.Show("Invalid ID or password, please try again!", "Info", MessageBoxButtons.OK);
}
}
I can see that you've executed the ExecuteScalar method before opening the SQL Database connection, resulting in error you're getting.
Open the connection before ExecuteScalar method, and you're done.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\hp\documents\visual studio 2015\Projects\PersonalFinancialSoftware\PersonalFinancialSoftware\Login.mdf;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT COUNT (*) FROM Table where UserID = #userid AND Password = #password";
cmd.Parameters.AddWithValue("#userid", textBox1.Text);
cmd.Parameters.AddWithValue("#password", textBox2.Text);
object result = cmd.ExecuteScalar();
string useridlogin = Convert.ToString(result);
conn.Close();
if (useridlogin != " ")
{
Home_Page homepage = new Home_Page();
homepage.Show();
}
else
{
MessageBox.Show("Invalid ID or password, please try again!", "Info", MessageBoxButtons.OK);
}
}
You have open connection after ExecuteScalar thats you are getting error, You must open connection befor ExecuteScalar try this code
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\hp\documents\visual studio 2015\Projects\PersonalFinancialSoftware\PersonalFinancialSoftware\Login.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
conn.Open();
cmd.CommandText = "SELECT COUNT (*) FROM Table where UserID = #userid AND Password = #password";
cmd.Parameters.AddWithValue("#userid", textBox1.Text);
cmd.Parameters.AddWithValue("#password", textBox2.Text);
object result = cmd.ExecuteScalar();
string useridlogin = Convert.ToString(result);
conn.Close();
if (useridlogin != " ")
{
Home_Page homepage = new Home_Page();
homepage.Show();
}
else
{
MessageBox.Show("Invalid ID or password, please try again!", "Info", MessageBoxButtons.OK);
}
}
In your code SQL query find connection. But you have open it after ExecuteScalar so this is giving you an error.
I've written this registration form which adds data to my SQL Server database. What I want is an exception when the user enters a username that is already in the database.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn2.Open();
string CheckUser = "select Username from UserData where Username like #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn2);
com2.Parameters.AddWithValue("#Username", "'%"+ UsernameTextBox.Text +"%'");
com2.ExecuteNonQuery();
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
conn2.Close();
if (IsMatch == 0)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string InsertQuery = "insert into UserData (Username, Email, Password, Country) values (#Username, #Email, #Password, #Country)";
SqlCommand com = new SqlCommand(InsertQuery, conn);
com.Parameters.AddWithValue("#Username", UsernameTextBox.Text);
com.Parameters.AddWithValue("#Email", EmailTextBox.Text);
com.Parameters.AddWithValue("#Password", PasswordTextBox.Text);
com.Parameters.AddWithValue("#Country", CountryDropDownList.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
conn.Close();
}
else
{
Response.Write("User Already Exists!");
}
}
catch (Exception ex)
{
Response.Write(Convert.ToString(ex));
}
}
When I run it, I get an exception on the following line:
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
Blam's second solution works, but the IsMatch can be simplified a bit by casting to int instead of going to string and parsing.
This should also be handled at the database level. Set a primary key on your username column:
ALTER TABLE UserData ADD CONSTRAINT
PK_UserData PRIMARY KEY CLUSTERED (Username)
If you do it this way, then you don't even have to check for duplicates explicitly, you can just try to create the user and handle the exception if it fails:
try
{
using (var conn = new SqlConnection((ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString)))
{
conn.Open();
#if DOUBLE_CHECK
string CheckUser = "select count(*) from UserData where Username = #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn);
com2.Parameters.AddWithValue("#Username", UsernameTextBox.Text);
if ((int)com2.ExecuteScalar() > 0)
{
Response.Write("User already exists");
return;
}
#endif
string InsertQuerry = "insert into UserData (Username,Email,Password,Country) values (#Username,#Email,#Password,#Country)";
SqlCommand com = new SqlCommand(InsertQuerry, conn);
com.Parameters.AddWithValue("#Username", UsernameTextBox.Text);
com.Parameters.AddWithValue("#Email", EmailTextBox.Text);
com.Parameters.AddWithValue("#Password", PasswordTextBox.Text);
com.Parameters.AddWithValue("#Country", CountryDropDownList.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
}
}
catch (SqlException se)
{
if (se.Errors.OfType<SqlError>().Any(e => e.Number == 2627))
{
Response.Write("User already exists");
}
else
{
Response.Write(se.ToString());
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
If you handle the exception this way, the #if DOUBLE_CHECK section is redundant and can be removed. An attempt to add duplicate name will cause a SQL error and exception, and this will detect and handle the "duplicate key" error.
Two unrelated notes on your code:
Response.Redirect() will abort the current thread and your conn.Close() will not be called. Use a using() to ensure it's called.
Storing a password in the database as plain text is a disaster waiting to happen. PLEASE take a look at Best way to store password in database for some ideas about how to do this correctly
That won't return an integer
string CheckUser = "select count(*) from UserData where Username like #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn2);
com2.Parameters.AddWithValue("#Username", "'%"+ UsernameTextBox.Text +"%'");
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
And you don't need to use two different connections.
Just use one and close it in a Finally.
string CheckUser = "select count(*) from UserData where Username = #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn2);
com2.Parameters.AddWithValue("#Username", UsernameTextBox.Text );
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
This returns 0 or 1. This should fix your issue. Looks like you need to return an int type. Or you could change it to bool if you want. Either way, this sql statement should help! :)
select
isnull(convert(bit,(select top 1 case
when username != '' then 1
else 0 end
from UserData
where username like #Username)),0)
The database is not storing information all on the same row. On the first page, when I click the button it records it and that's fine, it's stored. Then on the next page, when i click the button, it stores the information, but on a different row? Any solutions? Heres the problem, and code below.
PAGE 1
public void addInformationToDatabase()
{
string Sex = ddlGender.Text;
string Name = tbxName.Text;
string DOB = tbxDOB.Text;
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.Connection = Con;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO [User] (GenderID,Name,DOB) VALUES(#Sex,#Name,#DOB)";
command.Parameters.AddWithValue("#Sex", Sex);
command.Parameters.AddWithValue("#Name", Name);
command.Parameters.AddWithValue("#DOB", DOB);
try
{
Con.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
Con.Close();
}
}
2ND PAGE
public void save()
{
string checkboxSelection = CheckBoxList1.SelectedItem.ToString();
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionString);
SqlCommand c = new SqlCommand();
c.Connection = Con;
c.CommandType = CommandType.Text;
c.CommandText = "INSERT INTO [User] (Ans1) VALUES(#Ans1)";
c.Parameters.AddWithValue("#Ans1", checkboxSelection);
try
{
Con.Open();
c.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
Con.Close();
}
}
Any help appreciated
your first page needs to get the ID back following the insert and then your second page needs to do an update based on that ID, not a subsequent insert.
There are a lot of resources about getting ids back - e.g How to get last inserted id?
(I'm assuming the id field uniquely identifies your row)
first query -
c.CommandText = "INSERT INTO [User] (Ans1) VALUES(#Ans1); SELECT SCOPE_IDENTITY()";
...
int userID = (Int32) c.ExecuteScalar();
you'll need to pass that ID to your 2nd page and change the insert to be an update:
"UPDATE User] SET Ans1 = #Ans1 WHERE Id = #id";
you'll also need to add the id as a parameter
c.Parameters.AddWithValue("#id", userID);
I have some trouble to update my sql server 2005 database when i use parameters.Here you can see the code that normally has to work.I precise that i already make others treatments such as insert into and it worked perfectly.
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
//Execute la commande
myCommand.ExecuteNonQuery();
EDIT:When i use hard code such as:
myCommand.CommandText = "Update Action set titre='title' where pk=#Pk";
it works...
I don't know where you went wrong this is the working code for me
string strCon = #"Data Source=SYSTEM19\SQLEXPRESS;Initial Catalog=TransactionDB;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection cn = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand("select * from tblTransaction1", cn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
txtName.Text = ds.Tables[0].Rows[i]["FirstName"].ToString();
txtName1.Text = ds.Tables[0].Rows[i]["LastName"].ToString();
}
}
}
Button click code
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(strCon);
obj1.FirstName = txtName.Text;
obj1.LastName = txtName1.Text;
if (obj1.upDate(cn))
{
}
}
Sample class code file
private bool m_flag = false;
private string strFirstName;
private string strLastName;
public string FirstName
{
get { return strFirstName; }
set { strFirstName = value; }
}
public string LastName
{
get { return strLastName; }
set { strLastName = value; }
}
public bool upDate(SqlConnection con)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
cmd.Parameters.AddWithValue("#Fname", FirstName);
cmd.Parameters.AddWithValue("#Lname", LastName);
cmd.CommandText = "Update tblTransaction1 set LastName=#Lname where FirstName=#Fname";
if (cmd.ExecuteNonQuery() > 0)
{
m_flag = true;
}
}
catch
{
}
return m_flag;
}
Sample Images
I've seen weird results when you forget to include the "CommandType" parameter. Since you using inline SQL, it should be set to "CommandType.Text".
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
// Added CommandType //
myCommand.CommandType = CommandType.Text;
//Execute la commande
myCommand.ExecuteNonQuery();
I have noticed that copying the entire code into a new project helps. I have ran into many times my code would work and then the next day would not, or would only work for someone else and not me. Usually this is due to the designer side of the project when adding and removing code from your project. Just because you delete specific code does not mean the program can update the entire class/project.
If you do :
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
What does it say ?
Try also to prefix your Action table, with the schema name, for example :
myCommand.CommandText = "Update MySchema.Action set titre=#Titre where pk=#Pk";
Because sometimes it can depend on the schema and the user's rights to update this schema.
You could try this: instead of adding the parameters like that
myCommand.Parameters.AddWithValue("#Titre", this.titre);
you should add them with data type.
myCommand.Parameters.Add(new SqlParameter("#Titre", SqlDbType.VarChar, 50));
myCommand.Parameters["#Titre"].Value = this.titre;
That way, the final SQL will be Update Action set titre='titre' instead of Update Action set titre=title. Look that in the second statement titre is not inside quotes ''.
Try adding the parameters after declaring the command.
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
//Execute la commande
myCommand.ExecuteNonQuery();
I found something similar (not identical) here: http://forums.asp.net/t/1249831.aspx/1
I am using the follwing code to update a person's email and password in the db. I have a datagridview which has only one row. When I hit the Update button, nothing happens - the page is refreshed and the values in the textboxes go back to what they were before....the update is not working. Please help. Thanks!
protected void btnUpdateAccount_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "UPDATE Member SET [Email] = #email, [Password] = #password WHERE [MemberID] = '" + mem_id + "'";
TextBox email = email = (TextBox)Gridview1.Rows[0].FindControl("user_email");
TextBox password = (TextBox)Gridview1.Rows[0].FindControl("user_password");
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#email", SqlDbType.VarChar);
cmd.Parameters.Add("#password", SqlDbType.VarChar);
cmd.Parameters["#email"].Value = email.Text;
cmd.Parameters["#password"].Value = password.Text;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error: ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
cmd.ExecuteNonQuery();
it return an integer value, so you can put.
int i = cmd.ExecuteNonQuery();
and see what it is returning, also you can use finally after catch to make sure the db con is closed. here you are just using it in the catch, also try to put break point and see if the parameter are passed in correct way and follow it till the end.
like
finally
{
if (con != null)
{
con.Close();
}
}
You need to bind the data from database again to get the new changes. grid view .bind()
There are a number of things that could be happening.
1) The btnUpdateAccount_Click event is never raised. To fix this, make sure the asp:Button tag has an OnClick="btnUpdateAccount_Click" attribute set.
An exception is being thrown and that you're not noticing.
The database is being updated, but you did not load/bind the data again to display the updated values.
Make sure to put in your PageLoad Clause
** Change Made **
As per #marc_s comment changed if(this.IsPostBack == true) to if(this.IsPostBack)
this.IsPostBack is boolean.
if(this.IsPostBack)
{
//dont load page
}