SqlCommand update doesn't update/insert - c#

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

Related

Get Values from Database based on one textbox in a registration form

I am making a basic web form with basic fields like name, email, number.
I just want, when i enter the number, rest of the fields are populated in the other textboxes based on that number from sql server.
Any help would be appreciated.
Code is as follows :
string ConnectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
string cmd = "IF NOT EXISTS(Select * from tbl_registration where Email = #Email OR MobileNo = #MobileNo) insert into tbl_registration values(#FirstName, #LastName,#Email,#MobileNo,#Address_1,#Address_2,#City,#State)";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using(SqlCommand com = new SqlCommand(cmd, con))
{
com.Parameters.AddWithValue("#FirstName", txtfname.Text.Trim());
com.Parameters.AddWithValue("#LastName", txtlname.Text);
com.Parameters.AddWithValue("#Email", txtemail.Text);
com.Parameters.AddWithValue("#MobileNo", txtmob_no.Text);
com.Parameters.AddWithValue("#Address_1", txtaddress1.Text);
com.Parameters.AddWithValue("#Address_2", txtaddress2.Text);
com.Parameters.AddWithValue("#City", txtcity.Text);
com.Parameters.AddWithValue("#State", txtstate.Text);
con.Open();
int success = com.ExecuteNonQuery();
if (success > 0)
{
Response.Write("<script>alert('Registration successfull')</script>");
}
else
{
Response.Write("<script>alert('Registration Not Sucessfull')</script>");
}
}
}
}
You should write the method definition as shown below on the text box changed event.
This is not the complete query answer. Here is a reference for you.
using (SqlConnection conn = new SqlConnection(CSs))
{
string query = "Your SQL Query here";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "sometablename");
firstnametext.Text = Convert.ToString(ds.Tables["sometablename"].Rows[0]["Firstname"]);
}
Here you need to properly handle the null for the data table.

C# and Access database doesn't insert/save my data

I wrote an application with C# and MS Access. I have my form login which it works. OK. And I have an insert statement which does not throw any error, but everything I enter into my textbox doesn't get inserted into my database, and when I want to make an update, it returns the same as insert statement, I mean no error, but the row is not inserted or updated.
string stringcon = System.Configuration.ConfigurationManager.ConnectionStrings["rent"].ConnectionString;
private void validateaddmember_button_Click(object sender, EventArgs e)
{
addmember.Visible = false;
MemoryStream ms = new MemoryStream();
pictureBox4.Image.Save(ms, pictureBox4.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
OleDbConnection con = new OleDbConnection(stringcon);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "INSERT INTO [team]([Firstname],[Lastname],[Email],[Password],[Function],[Role],[Registerdata],[Personaldescription],[Phonenumber],[Picture]) VALUES(#f,#l,#e,#p,#fu,#r,#reg,#per,#ph,#pic) ";
cmd.Parameters.AddWithValue("#f", firstname_textbox.Text);
cmd.Parameters.AddWithValue("#l", lastname_textbox.Text);
cmd.Parameters.AddWithValue("#e", email_textbox.Text);
cmd.Parameters.AddWithValue("#ph", phone_textbox.Text);
cmd.Parameters.AddWithValue("#fu", function_textbox.Text);
cmd.Parameters.AddWithValue("#r", role_dropbox.selectedValue);
cmd.Parameters.AddWithValue("#reg", DateTime.Now.ToString("dd-MM-yyyy HH: mm:ss"));
cmd.Parameters.AddWithValue("#per", richTextBox1.Text);
cmd.Parameters.AddWithValue("#p", repeatpassword_textbox.Text);
cmd.Parameters.AddWithValue("#pic", a);
cmd.ExecuteNonQuery();
con.Close();
}
And here I have in other form my update.
string stringcon = System.Configuration.ConfigurationManager.ConnectionStrings["rent"].ConnectionString;
private void bunifuFlatButton1_Click(object sender, EventArgs e)//login method
{
OleDbConnection con = new OleDbConnection(stringcon);
OleDbCommand cmd2 = new OleDbCommand();
cmd2.Parameters.Clear();
cmd2.Connection = con;
cmd2.CommandText ="update [team] set [Numberoflogin] = [Numberoflogin] + 1 where [Email]=#LEMAIL";
cmd2.Parameters.AddWithValue("#LEMAIL", materialSingleLineTextField1.Text);
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
Along with marc_s's important note -- you switched phone and password, make sure you fix that -- you only need # in the sql string. So not
cmd.Parameters.AddWithValue("#f", firstname_textbox.Text);
but
cmd.Parameters.AddWithValue("Firstname", firstname_textbox.Text);
Use the field name (Firstname). #f is just a marker. With Access, you could write the sql string like so:
cmd.CommandText = "INSERT INTO [team]([Firstname],[Lastname],[Email],
[Password],[Function],[Role],[Registerdata],[Personaldescription],
[Phonenumber],[Picture]) VALUES(?,?,?,?,?,?,?,?,?,?)";
so when you add the parameter value, use the field name.
You could also open the connection right before cmd.ExecuteNonQuery();, like your update form.

Why does my code in my c# windows form not work?

Why does my grid view not refresh with data in it? It adds to the database but then clears my grid view and has nothing in it. It loads the form and I can enter information into it hit the add button and it adds to database but grid view refresh puts no data into it.
private void addButton_Click(object sender, EventArgs e)
{
string title = titleTextBox.Text;
string starring = starringTextBox.Text;
string year = yearTextBox.Text;
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=<PATH TO FILE>);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO dbo.Movie (Title, Starring, Year) VALUES (#title, #starring, #year)";
cmd.Parameters.AddWithValue("#Title", title);
cmd.Parameters.AddWithValue("#Starring", starring);
cmd.Parameters.AddWithValue("#Year", year);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
SqlDataAdapter MyDataAdapter = new SqlDataAdapter(cmd.CommandText, conn);
titleTextBox.Text = "";
starringTextBox.Text = "";
yearTextBox.Text = "";
titleTextBox.Focus();
movieTableAdapter.Fill(moviesDataSet.Movie);
movieBindingSource.DataSource = movieTableAdapter;
myDataGridView.DataSource = movieBindingSource;
myDataGridView.Refresh();
myDataGridView.Update();
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'moviesDataSet.Movie' table. You can move, or remove it, as needed.
this.movieTableAdapter.Fill(this.moviesDataSet.Movie);
}
SqlDataAdapter MyDataAdapter = new SqlDataAdapter("select query here", conn);
Pass select query to adapter. You are passing an insert 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.

Table not update with new data

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.
}

Categories

Resources