Reputation: 487
As of now here is my code:
protected void Button2_Click(object sender, EventArgs e)
{
using (SqlConnection scn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
{
scn.Open();
SqlCommand cmd = new SqlCommand(@"UPDATE UserData SET CreditRequest =
CAST(REPLACE(CreditRequest, ',', '') as int)
FROM CreditRequests Where Username=@Username;
SELECT CreditRequest FROM UserData
WHERE Username=@Username", scn);
cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = Session["New"];
object value = cmd.ExecuteScalar();
if (value != null)
txtCredit.Text = value.ToString();
}
}
}
However, when i look at my database, the credit request value is being inserted to the database and makes new ID's and everything is NULL
.
Example
ID NULL Username NULL Email NULL Contact NULL Creditrequest 5,000
Is there a way to insert the credit request value to the right username. What am i missing in my code?
Also, i want that credit request value to be shown in my textbox and i believe its this line of code?
if (value != null)
txtCredit.Text = value.ToString();
Upvotes: 0
Views: 77
Reputation: 216293
You are calling an INSERT statement that adds a new record. And no, adding a WHERE clause at the end, doesn't transform an insert statement in an update statement.
If you want to UPDATE an existing record then you call
SqlCommand cmd = new SqlCommand(@"UPDATE UserData SET CreditRequest =
(SELECT CAST(REPLACE(c.CreditRequest, ',', '') as int)
FROM CreditRequests c Where c.Username=@Username)", scn);
For the second part of your question, is not possible to get the return value of ExecuteScalar in this context because UPDATE doesn't select any record to return. If you want to get back that value you could issue two statement together separating them with a semicolon:
SqlCommand cmd = new SqlCommand(@"UPDATE UserData SET CreditRequest =
(SELECT CAST(REPLACE(c.CreditRequest, ',', '') as int)
FROM CreditRequests c Where c.Username=@Username);
SELECT CreditRequest FROM UserData u
WHERE u.Username=@Username", scn);
Both statements will be executed, but ExecuteScalar will be able to return the CreditRequest updated
Upvotes: 1