Table not update with new data - c#

rIdThere are two text boxes in page. One is for UserId and the other one is for email. Both are retrieved data from table aspnet_membership and are set 'read-only'.
For email text box, it will change read-only = false. Then user get to enter a new email then hit button save. It should update the email in table with the new email but unfortunately no changes made. Can some one tell me what should I remove/add to make it works. Here is my 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;
}
protected void Button4_Click(object sender, EventArgs e)
{
TextBox2.ReadOnly = false;
}
protected void Button3_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET Email = #email WHERE UserName = #id1", conn);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
cmd.Parameters.AddWithValue("#id1", TextBox3.Text);
}

I have refatored your code, now it should work
protected void Button3_Click(object sender, EventArgs e){
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET Email = #email WHERE UserName = #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();
}
}

Look like you forgot to open connection
con.Open();
run command
cmd.ExecuteNonQuery();
and then close connection
con.Close();

You code is showing no signs of committing any data back to its Data Source.
You need a Data Adapter, and you need to set its Insert Command to the command above.
SQLDataAdapter adapt = new SQLataAdapter();
you then need to open a connection :-
conn.open();
adapt.UpdateCommand = cmd;
adapt.UpdateCommand.ExecuteNonQuery()
conn.close();
Hope This Helps.

You can try directly updating the user via Membership class in your button click event:
protected void Button3_Click(object sender, EventArgs e)
{
var memUser = Membership.GetUser(TextBox3.Text) //Fetch the user by user Id
memUser.Email = TextBox2.Text // Assign the new email address
Membership.UpdateUser(memUser) // update the user record.
}

Related

SqlCommand update doesn't update/insert

I don't understand why this code doesn't update my SQL Server table data:
string stringcon = System.Configuration.ConfigurationManager.ConnectionStrings["devbuild"].ConnectionString;
public void Lastlogin()
{
SqlConnection con = new SqlConnection(stringcon); //CONNECTION
SqlCommand cmd2 = new SqlCommand();
cmd2.Parameters.Clear();
cmd2.Connection = con;
cmd2.CommandText = "update dbo.team set lastlogin=GETDATE() where email=#email";
cmd2.Parameters.AddWithValue("#email", emailtextbox.Text);
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
When I press the button "login button", nothing happens, absolutely nothing error, nothing updates..
Call function from button.
private void loginbutton_Click(object sender, EventArgs e)
{
Lastlogin();
}
Display the sqlstri goed cmd2.commandtext
Check if it's what you expected
The problem should be your where clause
Your parameters has to be exact the same as the email field

Check if username is in the database using ASP.Net

I want to check if a username is already in the database. It comes along with my update statement. I have this code and I do not know where to put the select statement:
protected void btn_update_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
con.Open();
str = "update UserData set Password=#Password where UserName='" + txtUser.Text + "'";
com = new SqlCommand(str, con);
com.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar));
com.Parameters["#Password"].Value = BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text);
com.ExecuteNonQuery();
con.Close();
Label1.Visible = true;
Label1.Text = "Password changed Successfully!" ;
con.Close();
}
I want something like
"Select Username from Userdata Where Username = txtUser.Text"
You don't need a SELECT here. ExecuteNonQuery() returns the number of rows affected, which means that when it returns 0, there was no user with the given name in the database. If all went well, it should return 1.
Your code is vulnerable to SQL injection and leaks resources. Here's a better version:
protected void btn_update_Click(object sender, EventArgs e)
{
using(var con = new SqlConnection(conn))
{
con.Open();
var commandTest = "update UserData set Password=#Password where UserName=#Username";
using(var com = new SqlCommand(commandTest, con))
{
com.Parameters.AddWithValue("#Username", txtUser.Text);
com.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
if(com.ExecuteNonQuery() == 1)
{
Label1.Visible = true;
Label1.Text = "Password changed Successfully!" ;
}
}
}
}

Insert Query in registration form

protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void registerBtn_Click1(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
outputlabel.Text = "Succesfully Registered";
myConnection.Open();
string query = "Insert into Users (FirstName,LastName,Gender,DateOfBirth,
Email_Id,Password) Values (#fn,#ln,#gen,#dob,#em,#pas)";
SqlCommand insertCommand = new SqlCommand(query, myConnection);
insertCommand.Parameters.AddWithValue("#fn", fname.Text);
insertCommand.Parameters.AddWithValue("#ln", lname.Text);
insertCommand.Parameters.AddWithValue("#gen", gender_dd.SelectedItem.Text);
insertCommand.Parameters.AddWithValue("#dob", date.Text);
insertCommand.Parameters.AddWithValue("#em", email.Text);
insertCommand.Parameters.AddWithValue("#pas", password.Text);
insertCommand.ExecuteNonQuery();
myConnection.Close();
}
}
}
}
Help me in this code..how can i edit this.If the same information is enter.Than code as show the message as already register.So no duplication in my database.
You need to run a SQL statement that checks if the user currently exists in the database before executing the INSERT into USERS statement.
So the code below will check if the user already exists based on the email address and password values they have supplied.
string userInvalid = "The username entered is invalid, please choose another."
string checkDatabase = "SELECT * FROM Users WHERE Email_Id = #em AND Password = #pas";
SqlCommand command = new SqlCommand(checkDatabase, myConnection);
command.Parameters.AddWithValue("#em", email.Text);
command.Parameters.AddWithValue("#pas", password.Text);
command.ExecuteNonQuery();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows) {
outputlabel.Text = userInvalid;
}
else
{
// execute your original SQL query
}

update asp.net text box

I have problem with updating data.
Sample:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string id = row.Cells[1].Text;
Response.Redirect("edit.aspx?id="+id);
}
after this code transition to another page with update cmd.
protected void Page_Load(object sender, EventArgs e)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
con.Open();
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.ExecuteNonQuery();
Response.Redirect("main.aspx");
}
I clicked button, and was redirected to main page. But nothing else, update doesn't work. :(
where do I have a problem?
I don't really know where is the problem, but for sure you need to refactor your update statement using the IDisposable capabilities of the connection object, it shoul look like this:
using (SqlConnection connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString))
{
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, connection);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
Your update sql query looks fine:
con.Open();
com.ExecuteNonQuery();
con.Close();
that is try using this function instead and debug it to see if there is a sql exception thrown.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
con.Open();
com.ExecuteNonQuery();
con.Close();
Response.Redirect("main.aspx");
}
catch (SqlException e)
{
}
}
UPDATE: Think I've realised why it's not working for you... you have a column called class... but class in sql server is a reserved keyword... so you must put square brackets around it ... like so
Edited the escaping (made a mistake as pointed out by Hans in the comment below)
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, [Class]=#Class WHERE ID=#ID";
The problem was found.Just add in Page_Load if(!isPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
Now, all working good.

radiobutton: how do i retrieve data from db

Access 2003 db
Field Name Data Type
CriminalOffence Text
VS 2010 C#
Using a groupbox, I can store data from radiobutton into my db. I have databinded both groupbox and radiobuttons to my db. When I use my nativgation buttons I see the data that has been stored where the groupbox text is. So the problem is I don't know how to properly retrieve data for the radiobutton. Retrieving data from textbox and combox is showing as it should be. Also when I want to insert new data the radiobutton does not get cleared. So...
I have two radiobuttons named, 1) rBYes 2) rBNo
I have the following method for inserting record...
private void btnInsert_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO Table1
(ID, AgeGroup, Gender, CriminalOffence)
VALUES(#txtID, #AcBAG, #cBGender, #CriminalOffence)", myCon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ID", txtID.Text);
cmd.Parameters.AddWithValue("#AgeGroup", cBAG.Text);
cmd.Parameters.AddWithValue("#Gender", cBGender.Text);
string str = "";
if (rBYes.Checked)
{
str = "Yes";
}
if (rBNo.Checked)
{
str = "No";
}
cmd.Parameters.AddWithValue("#CriminalOffence", SqlDbType.NVarChar).Value =
str;
}
And a method for creating a new record
private void btnNew_Click(object sender, EventArgs e)
{
txtID.Text = "";
cBAG.Text = "";
cBGender.Text = "";
rBYes.Text = "";
rBNo.Text = "";
}
An example of navigation button..
private void btnNextRec_Click(object sender, EventArgs e)
{
this.table1BindingSource.MoveNext();
}
ConnectionString...
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\..
\Database1.mdb");
Please can someone help me here, thanks in advance
Parameter names must match the parameters in the SQL insert statement.
private void btnInsert_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO Table1
(ID, AgeGroup, Gender, CriminalOffence)
VALUES(#ID, #AgeGroup, #Gender, #CriminalOffence)", myCon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ID", txtID.Text);
cmd.Parameters.AddWithValue("#AgeGroup", cbAG.Text);
cmd.Parameters.AddWithValue("#Gender", cbGender.Text);
cmd.Parameters.AddWithValue("#CriminalOffence", ((rBYes.Checked)? "Yes":"No"));
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}

Categories

Resources