I have registration as my database table. I want to update my information that has key in by the user into my SQL Server database. But it won't work, it don't occur any errors but the data key in wouldn't update into my database. Someone please help me if anything wrong with my code? Thanks.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UPDATE registration SET username = #username, password = #password, retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address, city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno", con);
con.Open();
cmd.Parameters.AddWithValue("#username", TextBoxUsername.Text);
cmd.Parameters.AddWithValue("#password", TextBoxPassword.Text);
cmd.Parameters.AddWithValue("#retypepassword", TextBoxRPassword.Text);
cmd.Parameters.AddWithValue("#gender", DropDownListGender.Text);
cmd.Parameters.AddWithValue("#birth", DropDownListDay.Text);
cmd.Parameters.AddWithValue("#address", TextBoxAddress.Text);
cmd.Parameters.AddWithValue("#city", TextBoxCity.Text);
cmd.Parameters.AddWithValue("#country", DropDownListCountry.Text);
cmd.Parameters.AddWithValue("#postcode", TextBoxPostcode.Text);
cmd.Parameters.AddWithValue("#email", TextBoxEmail.Text);
cmd.Parameters.AddWithValue("#carno", TextBoxCarno.Text);
cmd.ExecuteNonQuery();
con.Close();
if (IsPostBack)
{
Response.Redirect("UpdateSuccess.aspx");
}
After I click confirm it somehow only update my column gender which from male to female, others column of data it won't update.
It might be because the #username is used both in UPDATE and WHERE. If it changes, the WHERE will be wrong and if it does not change it can be left out of the query.
sql update
SqlCommand cmd = new SqlCommand("update[Testing].[dbo].[student] set name= '" + tb1.Text + "',age='" + tb2.Text + "',mobile='" + tb3.Text+ "' where id = '" + tb4.Text + "'", con);
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT * FROM registration WHERE username = " + TextBoxUsername.Text + "UPDATE registration SET username = #username, password = #password, retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address, city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno", con);
con.Open();
cmd.Parameters.AddWithValue("#username", TextBoxUsername.Text);
cmd.Parameters.AddWithValue("#password", TextBoxPassword.Text);
cmd.Parameters.AddWithValue("#retypepassword", TextBoxRPassword.Text);
cmd.Parameters.AddWithValue("#gender", DropDownListGender.Text);
cmd.Parameters.AddWithValue("#birth", DropDownListDay.Text);
cmd.Parameters.AddWithValue("#address", TextBoxAddress.Text);
cmd.Parameters.AddWithValue("#city", TextBoxCity.Text);
cmd.Parameters.AddWithValue("#country", DropDownListCountry.Text);
cmd.Parameters.AddWithValue("#postcode", TextBoxPostcode.Text);
cmd.Parameters.AddWithValue("#email", TextBoxEmail.Text);
cmd.Parameters.AddWithValue("#carno", TextBoxCarno.Text);
cmd.ExecuteNonQuery();
con.Close();
if (IsPostBack)
{
Response.Redirect("UpdateSuccess.aspx");
}
I think in page load you are load again all data and Button1_Click run after page load and you lost are all data
you can try your code in page_load method
private void Page_Load()
{
if (IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UPDATE registration SET username = #username, password = #password, retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address, city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno " + "WHERE username = #username", con);
con.Open();
.
.
.
}
}
I have never seen that type of syntax. Usually if one is using parameters, one is using a stored proc (the best practice). If one is using inline SQL, one builds the SQL statement as a single text line and executes it. I would recommend recoding for one of those.
If you want to try what you've started, in your SQL, you probably need to declare all the variables first. For example
SqlCommand cmd = new SqlCommand("declare #username varchar(100), #password varchar(100),
#retypepassword varchar(100) #gender varchar(10), #birth date, #address varchar(100),
#city varchar(100) #country varchar(100), #postcode varchar(10), #email varchar(100),
#carno varchar(100) UPDATE registration SET username = #username, password = #password,
retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address,
city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno",
con);
Related
You get created in UserAcc, and i want to transfer UserID and UserName over to Login table.
CREATE TABLE UserAcc (
UserID INT NOT NULL,
UserName VARCHAR(100),
LastName VARCHAR(100),
FirstName VARCHAR(100),
Email VARCHAR(100),
PRIMARY KEY (UserID)
);
CREATE TABLE Login (
UserName VARCHAR(100),
PassW VARCHAR(100),
PRIMARY KEY (UserName),
UserID INT NOT NULL REFERENCES UserAcc(UserID)
);
Is there a way in sql or can u do it in c#?
I have tried this in c# but it failes alot
var connectionString = #"Data Source=DESKTOP-VFKRIT8;Initial Catalog=DatingApp;User ID=sqlconn;Password=12345";
string query = "INSERT INTO UserAcc(UserID, UserName, LastName, FirstName, Email) VALUES (#UserID, #UserName, #LastName, #FirstName, #Email);" +
"INSERT INTO Login(UserID, UserName) VALUES (#UserID, #UserName);";
SqlConnection cnn;
// ID();
IDte();
try
{
cnn = new SqlConnection(connectionString);
cnn.Open();
SqlCommand cmd = new SqlCommand(query, cnn);
cmd.Parameters.AddWithValue("#UserID", userid);
cmd.Parameters.AddWithValue("#UserName", usernamebox.Text);
cmd.Parameters.AddWithValue("#FirstName", fnamebox.Text);
cmd.Parameters.AddWithValue("#LastName", lnamebox.Text);
cmd.Parameters.AddWithValue("#Email", emailbox.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Du er nu oprettet");
cnn.Close();
}
You can use INSERT as in:
insert into login (UserId, UserName)
select UserId, UserName
from UserAcc;
Good day, thanks for the assistance previously. please am trying to POST records from my window form to database, am having challenges with it, how do i do it?
Below is the code snippet i coded it with
private void btnNext_Click(object sender, EventArgs e)
{
//Calling Window Work experience page
WorkExperience frm = new WorkExperience();
frm.ShowDialog();
string connectionString = #"Data Source=localhost;" +
"Initial Catalog=EmploymentDb;Integrated Security=true; User Instance=False";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.Connection = connection;
//command.CommandText
string sql = "INSERT INTO EmploymentDb " +
"(Id,Title, LastName, FirstName, MiddleName, Gender, Address, Email, City, State, MobileNumber, DateOfBirth, HomePhone, DistchargeCertNumber, SchoolAttended, NYSCStatus, AgeLimit) VALUES " +
"(#Id, #Title, #LastName, #FirstName, #MiddleName, #Gender, #Address, #Email, #City, #State, #MobileNumber, #DateOfBirth, #HomePhone, #DistchargeCertNumber, #SchoolAttended, #NYSCStatus, #AgeLimit)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Id", txtID.Text);
cmd.Parameters.AddWithValue("#Title", comboBoxtTitle.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#MiddleName", txtMiddleName.Text);
cmd.Parameters.AddWithValue("#Gender", comboBoxGender.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#City", comboBoxCity.Text);
cmd.Parameters.AddWithValue("#State", comboBoxState.Text);
cmd.Parameters.AddWithValue("#MobileNumber", txtMobileNo.Text);
cmd.Parameters.AddWithValue("#DateOfBirth", dateTimePickerDOB.Text);
cmd.Parameters.AddWithValue("#HomePhone", txtHomePhone.Text);
cmd.Parameters.AddWithValue("#DistchargeCertNumber", txtNYSCCertNumder.Text);
cmd.Parameters.AddWithValue("#SchoolAttended", txtSchoolAttended.Text);
cmd.Parameters.AddWithValue("#NYSCStatus", comboBoxNYSCStatus.Text);
cmd.Parameters.AddWithValue("#AgeLimit", cbxAgeLimit.Text);
int affectedRows = cmd.ExecuteNonQuery();
MessageBox.Show(affectedRows + "Row inserted!");
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds, "Employment");
FillControls();
btnNext.Enabled = true;
// btnPrevious.Enabled = true;
}
You need to provide SqlConnection for SqlDataAdapter, if you want to retrieve the data back. Otherwise, you can delete the following 4 lines of code.
var query = "SELECT Id,Title FROM EmploymentDb";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
^^^^^^
DataSet ds = new DataSet();
da.Fill(ds, "Employment");
I am using a GridView, and I followed instructions here: http://www.aspsnippets.com/Articles/GridView-CRUD-Select-Insert-Edit-Update-Delete-using-Single-Stored-Procedure-in-ASPNet.aspx
Now I am getting the error: Procedure or function 'spRegistrantsGridView' expects parameter '#RegistrantId', which was not supplied
This is my StoredProcedure:
ALTER PROCEDURE [dbo].[spRegistrantsGridView]
#Action nvarchar(10),
#RegistrantId int,
#FirstName nvarchar(20),
#LastName nvarchar(25),
#AddressLine1 nvarchar(50),
#AddressLine2 nvarchar(50),
#City nvarchar(30),
#State nvarchar(2),
#Zip nvarchar(10),
#Country nvarchar(20),
#Phone nvarchar(15),
#PhoneExt nvarchar(4),
#Email nvarchar(50),
#MemberId bigint,
#Comments nvarchar(300)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
--SELECT
IF #Action = 'SELECT'
BEGIN
SELECT RegistrantId,
FirstName,
LastName,
AddressLine1,
AddressLine2,
City,
State,
Zip,
Country,
Phone,
PhoneExt,
Email,
Comments
FROM Registrant
END
--INSERT
IF #Action = 'INSERT'
BEGIN
INSERT INTO Registrant(
FirstName,
LastName,
AddressLine1,
AddressLine2,
City,
State,
Zip,
Country,
Phone,
PhoneExt,
Email,
MemberId,
Comments)
VALUES (
#FirstName,
#LastName,
#AddressLine1,
#AddressLine2,
#City,
#State,
#Zip,
#Country,
#Phone,
#PhoneExt,
#Email,
#MemberId,
#Comments)
END
--UPDATE
IF #Action = 'UPDATE'
BEGIN
UPDATE Registrant SET
FirstName = #FirstName,
LastName = #LastName,
AddressLine1 = #AddressLine1,
AddressLine2 = #AddressLine2,
City = #City,
State = #State,
Zip = #Zip,
Country = #Country,
Phone = #Phone,
PhoneExt = #PhoneExt,
Email = #Email,
MemberId = #MemberId,
Comments = #Comments
WHERE RegistrantId = #RegistrantId
END
--DELETE
IF #Action = 'DELETE'
BEGIN
DELETE FROM Registrant
WHERE RegistrantId = #RegistrantId
END
END
And the part of my C# where it throws the error (specifically at sda.Fill(dt);):
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
The parameter #RegistrantId wasn't added when calling the stored procedure.
Add the parameter to your code like so:
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
{
cmd.CommandType = CommandType.StoredProcedure;
// missing parameter
cmd.Parameters.AddWithValue("#RegistrantId", [insert id]);
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
EDIT
Now your SP is in your question the issue is you have multiple parameters specified but you're only adding one in your c# code. Either remove the params from your SP or make them optional by adding = null
e.g.
ALTER PROCEDURE [dbo].[spRegistrantsGridView]
#Action nvarchar(10),
#RegistrantId int = null,
#FirstName nvarchar(20) = null,
...
Hi guys i came stuck again. I am wanting to edit a selected row from my datagridview and replace the data from dgv with the new information in the text fields. I have managed to get it to change all the data in the dataset. So what i am asking is for guidance on how to code it so it only edits the selected row.
private void btnEdit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = new SqlCommand(String cmdUpdate = #"update Customer set firstName = #firstName, surname = #surname, email = #email, phonenumber = #phone, mobileNumber = #mobile";
, con);
da.UpdateCommand.Parameters.Add("#firstName", SqlDbType.VarChar).Value = textFirstName.Text;
da.UpdateCommand.Parameters.Add("#surname", SqlDbType.VarChar).Value = textSurname.Text;
da.UpdateCommand.Parameters.Add("#email", SqlDbType.VarChar).Value = textEmail.Text;
da.UpdateCommand.Parameters.Add("#phone", SqlDbType.VarChar).Value = textPhone.Text;
da.UpdateCommand.Parameters.Add("#mobile", SqlDbType.VarChar).Value = textMobile.Text;
da.UpdateCommand.Parameters.Add("#ID", SqlDbType.Int).Value = customerDataSet.Customer[0].ID;
con.Open();
da.UpdateCommand.ExecuteNonQuery();
MessageBox.Show("Customer Edited");
con.Close();
}
You UPDATE query updates whole table you should use WHERE statement in this query to update the row
with current ID
update Customer
set firstName = #firstName,
surname = #surname,
email = #email,
phonenumber = #phone,
mobileNumber = #mobile
WHERE ID=#ID
I am working on a database management system. I have a simple task of updating user profile. I created an asp.net page with textboxes and a save button. After adding the text I click on the save button. The code for the button is
protected void Button1_Click(object sender, EventArgs e)
{
string firstName = TextBox2.Text;
string lastName = TextBox1.Text;
string sCourse = TextBox3.Text;
string sTelephone = TextBox4.Text;
string sAddress = TextBox5.Text;
string sEmail = TextBox6.Text;
string Gender = TextBox7.Text;
string user = User.Identity.Name;
OleDbConnection oleDBConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\ASPNetDB.accdb");
string sqlQuerry = "UPDATE aspnet_Users SET firstName=#firstName, lastName=#lastName, Gender=#Gender, Address=#Address, Telephone=#Telephone, Course=#Course, Email=#email WHERE UserName=#UserName";
OleDbCommand cmd = new OleDbCommand(sqlQuerry, oleDBConn);
cmd.Parameters.AddWithValue("#UserName", User.Identity.Name);
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#Course", sCourse);
cmd.Parameters.AddWithValue("#Telephone", sTelephone);
cmd.Parameters.AddWithValue("#Address", sAddress);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#Email", sEmail);
oleDBConn.Open();
cmd.ExecuteNonQuery();
}
But nothing happens. The database is not updated. Is the code correct?
Add the parameter values in the same order as the parameter names appear in the UPDATE statement.
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#Address", sAddress);
cmd.Parameters.AddWithValue("#Telephone", sTelephone);
cmd.Parameters.AddWithValue("#Course", sCourse);
cmd.Parameters.AddWithValue("#Email", sEmail);
cmd.Parameters.AddWithValue("#UserName", User.Identity.Name);
OleDb with Access does not pay attention to the parameter names, only their order.
add the parameters according to the order in the query
string sqlQuerry = "UPDATE aspnet_Users SET firstName=#firstName, lastName=#lastName, Gender=#Gender, Address=#Address, Telephone=#Telephone, Course=#Course, Email=#email WHERE UserName=#UserName";
OleDbCommand cmd = new OleDbCommand(sqlQuerry, oleDBConn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#Address", sAddress);
cmd.Parameters.AddWithValue("#Telephone", sTelephone);
cmd.Parameters.AddWithValue("#Course", sCourse);
cmd.Parameters.AddWithValue("#Email", sEmail);
cmd.Parameters.AddWithValue("#UserName", User.Identity.Name);