Updating data in database using datagridview - c#

i have a code like this:
public int updateFriend(long id, string Firstname, string Lastname, string Nickname, DateTime Birthdate, int Age, string Gender)
{
OleDbConnection con = new OleDbConnection(conString());
string query = "UPDATE FriendList SET Firstname ='" + Firstname + "', Lastname ='" + Lastname + "',Nickname ='" + Nickname + "',Birthday ='" + Birthdate + "',Age ='" + Age + "', Gender ='" + Gender + "' WHERE ID = " + id;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
return (rowsAffected);
}
now the problem is when i click the update button it calls the method updateFriend, then an error appears on the Line "int rowsAffected = cmd.ExecuteNonQuery();" saying
"No value given for one or more required parameters."
Can somebody help me with this?

string query = "UPDATE FriendList SET Firstname ='" + Firstname + "', Lastname ='" + Lastname + "',Nickname ='" + Nickname + "',Birthday ='" + Birthdate + "',Age ='" + Age + "', Gender ='" + Gender + "' WHERE ID = " + id;
You are passing all parameters as string where some of them are int and one is DateTime. As suggested you should use Parameters.AddWithValue()
string query = "UPDATE FriendList SET Firstname = #Firstname, Lastname = #Lastname , Nickname = #Nickname, Birthday = #Birthdate, Age = #Age, Gender = #Gender WHERE ID = #id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Firstname", FirstName);
//add rest parameters the same way as above
cmd.Parameters.AddWithValue("#id", id);

Talking about on your error message;
"No value given for one or more required parameters."
This message will appears probably one of your parameters is null or zero-length string. Or the reason can be misspelling of your parameters.
Check your query in your database first and look which column gives you an error.
And please, never add your parameters in your sql command. That may cause SQL Injection attack. Always use parameterized query on your queries.
Check out SqlParameterCollection.AddWithValue() method from MSDN.

Related

What am I missing? I can't figure out why it is adding the extra '.' System.Data.SqlClient.SqlException: 'Incorrect syntax near '76231'.'

private void buttonAdd_Click(object sender, EventArgs e)
{
String FirstName = textBoxFirstName.Text;
String LastName = textBoxLastName.Text;
String PhoneNumber = textBoxPhone.Text;
String Email = textBoxEmail.Text;
DateTime Birthday = DateBirthday.Value;
String Street = textBoxStreet.Text;
String City = textBoxCity.Text;
String State = textBoxState.Text;
String Zipcode = textBoxZipcode.Text;
if (
FirstName == "" ||
LastName == "" ||
PhoneNumber == "" ||
Email == ""
)
{
MessageBox.Show("Fields with '*' cannot be null");
}
else
{
SqlConnection con = new SqlConnection("Data Source=SER\\SQLEXPRESS;Initial Catalog=SunshineGrace;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO Customers
VALUES('" + FirstName + "', '" + LastName + "', '" + PhoneNumber + "', '" + Email + "', '" + Birthday + "', '" + Street + "', '" + City + "', '" + State + "', '" + Zipcode + "'",con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Customer Added!");
}
}
I'm trying to create a program that adds a column into my SQL database, I just cannot figure out why I am getting this error. I've tried reformating the insert command many different ways and changing the dateime to a textbox and its still throws the same error message.
You should really NEVER EVER EVER write SQL code like that! It leaves you wide open to SQL injection - the #1 vulnerability out there. Stop doing that RIGHT NOW!
Instead, use properly parametrized SQL queries, and also get in the habit of putting your disposable objects (like SqlConnection and SqlCommand) into proper using() { .. } code blocks to ensure proper disposal.
So your code should be something like this instead:
// define your INSERT query and use proper list of columns in the table you're inserting into
string query = #"INSERT INTO Customers(FirstName, LastName, PhoneNumber, Email, Birthday, Street, City, State, Zipcode)
VALUES(#FirstName, #LastName, #PhoneNumber, #Email, #Birthday, #Street, #City, #State, #Zipcode);";
// put connection and command objects into using blocks
using (SqlConnection con = new SqlConnection("Data Source=SER\\SQLEXPRESS;Initial Catalog=SunshineGrace;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand (query, con))
{
// define parameters, with their most appropriate data type, and set their values
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 100).Value = FirstName;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar, 100).Value = LastName;
cmd.Parameters.Add("#PhoneNumber", SqlDbType.VarChar, 50).Value = PhoneNumber;
cmd.Parameters.Add("#Email", SqlDbType.VarChar, 255).Value = Email;
cmd.Parameters.Add("#Birthday", SqlDbType.Date).Value = Birthday;
cmd.Parameters.Add("#Street", SqlDbType.VarChar, 100).Value = Street;
cmd.Parameters.Add("#City", SqlDbType.VarChar, 100).Value = City;
cmd.Parameters.Add("#State", SqlDbType.VarChar, 100).Value = State;
cmd.Parameters.Add("#Zipcode", SqlDbType.VarChar, 20).Value = Zipcode;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Customer added");
}
Using this code approach not only reliably eliminates any SQL injection risk, it also prevents any errors from having too many or too few single quotes etc. in your SQL statement. It's just good practice to go with this - always.

How to use select sub Query in insert statement?

I am trying to insert some values into a database, using insert statement. I have to use select statement as well to get from another table the key that corresponds to the option selected.
I tried several queries but none of them worked.
string query3 = "insert into students (FirstName, LastName, FatherName,
Email, DateBirth, DateReg, Adress, Gender, Specialization, Country,
Province, City) values ('"
+ this.txt_fname.Text + "','" + this.txt_lname.Text + "','"
+ this.txt_fathername.Text + "','" + this.txt_email.Text + "','"
+ this.date_birth.Text + "', '" + this.date_reg.Text + "','"
+ this.txt_adress.Text + "','" + this.Gender
+ "', (select specialization_id from specialization where SpecializationName = '" + this.specialization.Text
+ "'),
(select country_id from country where CountryName ='" + this.comboBox2.Text
+ "'),(select province_id from province where ProvinceName ='"
+ this.comboBox4.Text
+ "'),(select city_id from city where CityName ='"+ this.comboBox3.Text + "');";
I expect the output "saved" but I get {"Incorrect syntax near ';'."}
When I use:
'" + ("SELECT specialization_id from specialization where SpecializationName =" + this.specialization.Text)+ "'
instead of (wrote above):
(select specialization_id from specialization where SpecializationName = '" + this.specialization.Text + "')
I get:
{"Conversion failed when converting the varchar value 'SELECT specialization_id from specialization where SpecializationName =Informatica Economica' to data type int."}
My usual caveat, I'm not a C# programmer, I barely know it, but the documenation I linked before was more than enough for me to write this properly:
string commandText = "INSERT INTO dbo.student (FirstName, LastName, FatherName, Email, DateBirth,DateReg, Adress, Gender, Specialization, Country, Province,City) " +
"SELECT #FirstName,#LastName, #Fathername, #Email, #DateBirth, #DateReg, #Address, #Gender, s.specialization_id, c.country_id, p.province_id, cy.city_id " +
"FROM (SELECT specialization_id FROM dbo.specialization WHERE SpecializationName = #Specialization) s " +
"CROSS APPLY (select country_id from country where CountryName = #Country) c " +
"CROSS APPLY (select province_id from province where ProvinceName = #Province) p " +
"CROSS APPLY (select city_id from city where CityName = #City) cy;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add(#FirstName, SqlDbType.VarChar,50).Value = this.txt_fname.Text;
command.Parameters.Add(#LastName, SqlDbType.VarChar,50).Value = this.txt_lname.Text;
command.Parameters.Add(#Fathername, SqlDbType.VarChar,50).Value = this.txt_fathername.Text;
command.Parameters.Add(#Email, SqlDbType.VarChar,50).Value = this.txt_email.Text;
command.Parameters.Add(#DateBirth, SqlDbType.Date).Value = this.date_birth.Text; //Shouldn't this be a date picker object?
command.Parameters.Add(#DateReg, SqlDbType.Date).Value = this.date_reg.Text; //Shouldn't this be a date picker object?
command.Parameters.Add(#Address, SqlDbType.VarChar,200).Value = this.txt_adress.Text; //It's spelt Address (2 d's)
command.Parameters.Add(#Gender, SqlDbType.VarChar,10).Value = this.Gender; //Why did this not have the Text property?
command.Parameters.Add(#Specialization, SqlDbType.VarChar,50).Value = this.specialization.Text;
command.Parameters.Add(#CountryName, SqlDbType.VarChar,50).Value = this.comboBox2.Text; //You should name this combo box
command.Parameters.Add(#Province, SqlDbType.VarChar,50).Value = this.comboBox4.Text; //You should name this combo box
command.Parameters.Add(#City, SqlDbType.VarChar,50).Value = this.comboBox3.Text;//You should name this combo box
}

Cannot Update GridView

I have the codes up but when I try to update, it did not change anything. I am not sure where the problem went wrong
I have tried to change the index of email and others from 0-6 but when I use these index, everytime i tries to update, the email became UserID and so on.
Back End:
protected void gvAccount_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)gvAccount.Rows[e.RowIndex];
string UserID = gvAccount.DataKeys[e.RowIndex].Values["UserID"].ToString();
string Email = ((TextBox)row.Cells[1].Controls[0]).Text;
string FirstName = ((TextBox)row.Cells[2].Controls[0]).Text;
string LastName = ((TextBox)row.Cells[3].Controls[0]).Text;
string Password = ((TextBox)row.Cells[4].Controls[0]).Text;
string Point = ((TextBox)row.Cells[5].Controls[0]).Text;
string Role = ((TextBox)row.Cells[6].Controls[0]).Text;
SqlCommand cmd = new SqlCommand("UPDATE UserRegister set Email = '" + Email + "', FirstName = '" + FirstName + "', LastName = '" + LastName + "', Password = '" + Password + "',Point = '" + Point + "',Role = '" + Role + "' WHERE UserID =" + UserID, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
gvAccount.EditIndex = -1;
FillGrid();
}
There is no error message, but it just did not update anything. I am not sure if is the WHERE UserID = UserID problem. UserID is my primary key
I think you've mistaken to take the value. For Excel I use like this:
string email= row[1].ToString();
string firstName = row[2].ToString();
string lastName = row[3].ToString();
string pass= row[4].ToString();
string point = row[5].ToString();
string role = row[6].ToString();
*Update
Something's wrong with your SQL, for the query try somethings like this:
string con = #"Data Source=myServerAddress;Initial Catalog=myDataBase Integrated Security=SSPI;
User ID=myDomain\myUsername;Password=myPassword;";
string comm = #"Update... SET... WHERE...";
SqlCommand cmd = new SqlCommand(comm, con);
Gridview.Databind();

Inserting function in ASP.net is showing error and not executing the Insert query

Data comes from "Temp" table.
Stored in variables
Inserted into "Client" table with the addition of two more variables.
And there comes an error. The INSERT query is not executing properly.
Query,
int r;
string que = "INSERT INTO client (fname, lname, dob,
email, gender, uname, upass) VALUES
('" + fname + "',
'" + lname + "', '" + dob + "',
'" + email + "',
'" + gender + "',
'" + TextBox1.Text + "',
'" + TextBox2.Text + "') ";
r = c.savedeldata(que);
savedeldata Function
public int savedeldata(string qu)
{
con.Open();
cmd = new SqlCommand(qu, con);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
That's the only solution I can find.
if (ds.Tables["0"].Rows.Count == 1)
{
int r;
string queryt = "DELETE FROM tbl_client";
r = c.savedeldata(queryt);
string que = "INSERT INTO tbl_client(fname, lname, dob, email, gender) SELECT * FROM temp WHERE dob = '" + TextBox3.Text + "'";
r = c.savedeldata(que);
string quer = "UPDATE tbl_client SET uname = '"+ TextBox1.Text +"', upass = '"+ TextBox2.Text +"' WHERE dob = '"+ TextBox3.Text +"'";
r = c.savedeldata(quer);
}

How to UPDATE multiple times off one connection OleDb

I am trying to update an Access database with information I have passed to a [WebMethod] from multiple txtbox's on a website.
[WebMethod]
public string changePersonalInfo(string email, string name, string id, string address, string contactDetails, string password, string question, string answer, string loggedInEmail)
I am passing all information to it weather it has a value or not.
if (email != "") //Wont execute if there is no value
{
cmd.CommandText = #"UPDATE BuyerInfo SET [emailAddress] = '" + email + "' WHERE (emailAddress = '" + loggedInEmail + "')";
}
if (name != "")
{
cmd.CommandText = #"UPDATE BuyerInfo SET [name] = '" + name + "' WHERE (emailAddress = '" + loggedInEmail + "')";
}
if (id != "")
{
cmd.CommandText = #"UPDATE BuyerInfo SET [id] = '" + id + "' WHERE (emailAddress = '" + loggedInEmail + "')";
}
//etc. It goes on for a few more.
cmd.ExecuteNonQuery();
conn.Close();
The problem is when I run the website it only updates the data from the last txtbox on the website (so in other words the last variable that has a value). How do I fix this, or if there is maybe a better way to do it.
P.S Keep in mind I am new to Web Services.
Thanx

Categories