Database Update - c#

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
}

Related

Delete a record from database

I'm trying to delete record from data base MSSQL by entering the ID and hit delete btn. i didn't get any error and it give recorded deleted successful but once i check database i see the record doesn't deleted
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (txtImgID.Text == "")
{
Response.Write("Enter Image Id To Delete");
}
else
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString);
con.Open();
cmd = new SqlCommand("delete from certf where id=" + txtImgID.Text + "", con);
lblsubmitt.Text = "Data Deleted Sucessfully";
}
}
catch (Exception)
{
lblsubmitt.Text = "You haven't Submited any data";
}
}
var idToDelete = int.Parse(txtImgID.Text); // this is not necessary if the data type in the DB is actually a string
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("DELETE FROM [certf] WHERE id = #id", con))
{
// I am assuming that id is an integer but if it is a varchar/string then use the line below this one
// cmd.Parameters.Add("#id", SqlDbType.VarChar, 100).Value = txtImgID.Text;
cmd.Parameters.Add("#id", SqlDbType.Int32).Value = idToDelete;
cmd.ExecuteNonQuery();
}
You need to call ExecuteNonQuery which executes the query against the database.
Always use parameters instead of string concatenation in your queries. It guards against sql injection and ensures you never has issues with strings that contain escape characters.
I did not include any error handling or return messages but do note that you are throwing away all the good stuff in your excetion handler's catch block, you will never know why a query failed after this has executed.

Delete Command C# + SQL Server

I'm performing a command to erase data from a DataGridView
But I can not make it work, I just want to select a line and erase it
In addition to programming a button that says "Delete" so that when you click on it, the selected data in the DataGridView will be deleted
I need really help
I am lost
My Table is "Person"
My Column is "ID"
Instances
{SqlConnection cn;
SqlCommand cmd;
SqlDataReader dr;
SqlDataAdapter da;
DataTable dt;}
public string Del(int ID)
{
string ouk = "Delete Work";
try
{
cmd = new SqlCommand("Delete From Person Where = ID )", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
ouk = "Bad character:" + ex.ToString();
}
return ouk;
}
For Button Erase at DataGridView
private void buttondel_Click(object sender, EventArgs e)
{
MessageBox.Show(c.Del(TBID));
}
The issue is that your SQL query is malformed and that you're not passing the ID to the query:
"Delete From Person Where = ID )"
One side of the equality check is missing, and you have an unexpected closing bracket.
You should change your query to accept a parameter:
"Delete From Person Where ID = #id"
and then pass the parameter to your command:
cmd.Parameters.Add("#id", SqlDbType.Int).Value = ID;
So it becomes:
try
{
using (cmd = new SqlCommand("Delete From Person Where ID = #id", cn))
{
cmd.Parameters.Add("#id", SqlDbType.Int).Value = ID;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
ouk = "Bad character:" + ex.ToString();
}
I've taken the liberty of wrapping SqlCommand in a using statement so that it's disposed once we're done with it.

Deleting from a .mdb with input from textbox

My delete has the same issue where it says
no value given for one or more parameters
I actually don't know the code to fix this.
This is what I have atm:
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
string FirstName = txtFirstName.Text;
sql = " DELETE FROM Club_Member WHERE FirstName = #FirstName; ";
dbCmd = new OleDbCommand(sql, dbConn);
// Execute query
dbCmd.ExecuteNonQuery();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
string FirstName = txtFirstName.Text;
sql = " DELETE FROM Club_Member WHERE FirstName = #FirstName; ";
dbCmd = new OleDbCommand(sql, dbConn);
dbCmd .Parameters.Add(new OleDbParameter("#FirstName",FirstName ));
// Execute query
dbCmd.ExecuteNonQuery();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
Isn't that obvious?
You declared #FirstName parameter in your SqlCommand but you never add a value as a parameter.
dbCmd = new OleDbCommand(sql, dbConn);
dbCmd.Parameters.AddWithValue("#FirstName", FirstName);
Also use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection dbConn = new OleDbConnection(ConnString))
using(OleDbCommand dbCmd = dbConn.CreateCommand())
{
dbCmd.CommandText = "DELETE FROM Club_Member WHERE FirstName = #FirstName";
dbCmd.Parameters.AddWithValue("#FirstName", FirstName);
dbConn.Open();
dbCmd.ExecuteNonQuery();
}
I always prefer to use Add method instead of AddWithValue because AddWithValue method sends nvarchar type since it is a string variable. But in some cases, you don't want this. You want to declare your SqlDbType as well.
For example, if you have a varchar column and you used AddWithValue method, ADO.NET send it as an nvarchar value and that might cause potential information lost. (for non-Latin characters for example)
This happens mainly because of the Miss spelled values or if you leave any values blank while entering or adding. So database confuses it with a parameter. Debug or just check for spelling.
BTW I wanted to know what is primary key you are using for Club_Member?

Adding to a sql integer column using C#

I am trying to update a SQL table from my C# backend, but it never successfully executes; mainServiceButton is a pre-existing value in the linkName column. Here is what I have so far:
conn.Open();
string qry = "UPDATE clickStream SET clickCount = (clickCount + 1) WHERE linkName = mainServiceButton";
SqlCommand cmd = new SqlCommand(qry, conn);
try
{
cmd.ExecuteScalar();
}
catch
{
MessageBox.Show("not executed");
}
conn.Close();
This is how the table was created:
CREATE TABLE clickStream(
click_ID int identity(1,1),
linkName nvarchar(50) not null,
clickCount int,
PRIMARY KEY(click_ID));
The desired result is to increase the clickCount by 1 every time a link(linkName) is clicked on. Any Suggestions?
MessageBox.Show("not executed"); is not going to help you much except to obscure the details of the error: you need to instead output the details of the caught exception to understand what happened.
Addressing this and other suggestions made in comments...
mainServiceButton nakedly inline in the SQL text not possibly being what you want
a SqlParameter being warranted to accept a value for the WHERE sanely
ExecuteNonQuery() instead of ExecuteScalar() being the right call
..., see what sort of mileage you get with this instead:
conn.Open();
string qry = "UPDATE clickStream SET clickCount = (clickCount + 1) WHERE linkName = #linkName";
SqlCommand cmd = new SqlCommand(qry, conn);
// Use a SqlParameter to correct an error in the posted code and do so safely.
cmd.Parameters.Add(new SqlParameter("#linkName", "mainServiceButton"));
try
{
cmd.ExecuteNonQuery(); // not ExecuteScalar()
}
catch (SqlException sex)
{
// Output the exception message and stack trace.
MessageBox.Show(sex.ToString());
}
conn.Close();
Try the below, not tested so you may need to fix minor bugs:
conn.Open();
string qry = "UPDATE clickStream SET clickCount = (clickCount + 1) WHERE linkName = 'mainServiceButton';SELECT ##ROWCOUNT;";
SqlCommand cmd = new SqlCommand(qry, conn);
try
{
int rowsAffected = (int)cmd.ExecuteScalar();
if (rowsAffected != 1)
throw new ApplicationException("Rows affected should be 1, " + rowsAffected + " were affected.");
}
catch (Exception ex)
{
MessageBox.Show("Not executed successfully, exception: " + ex.ToString());
}
conn.Close();

Unable to update data into SQL table

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();

Categories