How to update only some columns of database? - asp.net

The problem occuring on updating only email all other blanks get null . Even if i unchecked allow null in sql server 2008 .my code is-
protected void Updateinfo_Click(object sender, EventArgs e)
{
string radiogender;
if (Radiochngmale.Checked == true)
radiogender = Radiochngmale.Text.ToString();
else
radiogender = Radiochngfemale.Text.ToString();
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["Con"].ConnectionString;
con.Open();
if (con.State == ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand();
Random r = new Random();
int next = r.Next();
if (FileUpload2.HasFile)
{
string myMap = MapPath("~/").ToLower();
string ImageName = FileUpload2.PostedFile.FileName;
sImageFileExtension = ImageName.Substring(ImageName.LastIndexOf(".")).ToLower();
if (sImageFileExtension == ".gif" || sImageFileExtension == ".png" || sImageFileExtension == ".jpg" || sImageFileExtension == ".jpeg" || sImageFileExtension == ".bmp")
{
string ImageSaveURL = myMap + "UserImage/" + next + sImageFileExtension;
FileUpload2.PostedFile.SaveAs(ImageSaveURL);
}
else
Response.Write("Invalid File");
}
cmd.Connection = con;
if(chngfname.Text==null)
chngfname.Text="Select Firstname from Login where Email='"+Session["UserName"]+"'";
if (chnglastname.Text == null)
chnglastname.Text = "Select Lastname from Login where Email='" + Session["UserName"] + "'";
if (chngage.Text == null)
chngage.Text = "Select age from Login where Email='" + Session["UserName"] + "'";
if (chngemail.Text == null)
chngemail.Text = "Select Email from Login where Email='" + Session["UserName"] + "'";
if (radiogender == null)
radiogender = "Select gender from Login where Email='" + Session["UserName"] + "'";
if (chngpassword.Text == null)
chngpassword.Text = "Select Password from Login where Email='" + Session["UserName"] + "'";
if ( FileUpload2.HasFile==null)
sImageFileExtension = "Select profile_pic from Login where Email='" + Session["UserName"] + "'";
if (chngfname.Text == null)
chngfname.Text = "Select Firstname from Login where Email='" + Session["UserName"] + "'";
cmd.CommandText = "Update Login set FirstName = '"+chngfname.Text+"',LastName='"+chnglastname.Text+"',Email='"+chngemail.Text+"',Password='"+chngpassword.Text+"' ,gender='"+radiogender+"',age='"+chngage.Text+"' , profile_pic='"+ next + sImageFileExtension + "' where Email='"+Session["UserName"]+"'";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
Why didn't it is taking the previous values even if i mentioned it to take.Please check it out and sort it out

This is happening because TextBox.Text is never null so your SQL query ends up looking like this:
Update Login
set FirstName = '',
LastName = '',
where Email = 'John.doe#nowhere.net'
-- etc...
Except for the one or two fields where the data is actually set to something. Here's probably what you wanted it to look like:
update login
set FirstName = 'John',
LastName = (select Lastname from login where email = 'John.doe#nowhere.net'),
etc...
where email = 'John.doe#nowhere.net'
But, there no need for the subqueries. If you want to avoid overwriting values where a value is null or empty string, then you want your SQL to look like the following, use Parameters and set them to DbNull when the textbox is empty.
cmd.Parameters.AddWithValue("#FirstName", (chngfname.Text == String.Empty) ? DbNull.Value : chngfname.Text;
update login
set FirstName = coalesce(#firstName, FirstName),
LastName = coalesce(#LastName, LastName),
etc...
where Email = #Email
The other option is select the record first (which I'm sure you've already done) and simply use the same value that's already in the database.
if (chngfname.Text == String.Empty) chngfname.Text = Session["CurrentUserEntity"].FirstName;
Additionally, you need to change this to a parametrized query:
string sql = "update login set FirstName = #firstName, LastName = #lastName, etc... where email = #email;
cmd.Parameters.Add(...);

You should try to use a parametrized query instead of the current string concatenation method.
This will resolve the quoting problems and prevent sql injiection attacks
cmd.CommandText = "Update Login set FirstName = #First, LastName=#Last, " +
"Email=#Mail, Password=#Pass, gender=#Gend,age=#Age, " +
"profile_pic=#Prof " +
"where Email=#oldMail";
cmd.Parameters.AddWithValue("#First", chngfname.Text);
cmd.Parameters.AddWithValue("#Last", chnglastname.Text);
cmd.Parameters.AddWithValue("#Mail", chngemail.Text);
cmd.Parameters.AddWithValue("#Pass", chngpassword.Text);
cmd.Parameters.AddWithValue("#Gend", radiogender);
cmd.Parameters.AddWithValue("#Age", chngage.Text);
cmd.Parameters.AddWithValue("#Prof", next + sImageFileExtension );
cmd.Parameters.AddWithValue("#oldMail", +Session["UserName"]);
However, as I have said in my previous comment, your code doesn't seems correct.
First a TextBox.Text cannot be null, it is an empty string. This will skip your text for null values above and you end with setting a blank value in the database. At least try to change the test with
if(string.IsNullOrEmpty(chngfname.Text))
......
But at this point you should change the code inside each if above. If your intentions is to retrieve the old values from the database and use them in case of empty string, you need to execute that string, not store it in the textbox.
EDIT: Before to start your update process you need to load the old values of the record you are trying to update. This could be done using the same connection
SqlDataAdapter da = new SqlDataAdapter("SELECT * from Login where EMail = #oldMail", con);
da.SelectCommand.Parameters.AddWithValue("#oldMail", Session["UserName");
DataTable dt = new DataTable();
da.Fill(dt);
now you have in a datatable all of your old values for that user, so when you reach the check of the old values you could write something like this
if(string.IsNullOrEmpty(chngfname.Text))
cngfname.Text = (dt.Rows["FirstName"] == DBNull.Value ? string.Empty : dt.Rows["FirstName"].ToString());
and remove that sql string because you have already retrieved the values for every potentially missing field

Related

"Incorrect syntax near 'admin'

this programm when i enter username and password go to data base and compare from table,but when i enter username admin ,password admin(exist in table)
compalier show error "Incorrect syntax near 'admin'" in line
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser,conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "select Password from Users where Password'" + TextBoxPassword.Text + "'";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
string password = passComm.ExecuteScalar().ToString();
if (password == TextBoxPassword.Text)
{
//Session["NEW"] = TextBoxUserName.Text;
Response.Redirect("Welcome.aspx");
}
else
{
Response.Redirect("Error.aspx");
}
}
The error is simply caused by the missing equals before the values concatenated in the sql command text.
But also fixing it, your code is wrong for other reasons.
You should ALWAYS use a parameterized query to avoid Sql Injection and parsing problems,
You could remove the COUNT function that causes an unnecessary load of all records just to confirm the existence of your searched data
You need to identify your user searching for both password and
username on the SAME record, as it is now, the code above search first the username
and then a password, but I can type an existing user name (first if passed) and use
a password of a different user (second if passed) and then gain access to
your site.
.
string checkuser = "IF EXISTS(select 1 from [Users] where Username = #usr AND Password=#pwd)
SELECT 1 ELSE SELECT 0";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand com = new SqlCommand(checkuser,conn))
{
conn.Open();
com.Parameters.AddWithValue("#usr", TextBoxUserName.Text);
com.Parameters.AddWithValue("#pwd", TextBoxPassword.Text);
int temp = Convert.ToInt32(com.ExecuteScalar());
if (temp == 1)
Response.Redirect("Welcome.aspx");
else
Response.Redirect("Error.aspx");
}
Other things changed in the example above are the USING STATEMENT to be sure that your connection and command are disposed at the end of the operation also in case of exceptions
Try changing this line
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
to this
string checkuser = "select count(*) from [Users] where Username = '" + TextBoxUserName.Text + "'";
you are missing an = sign
you'll need to do the same to your password select as well, you also missed the = sign there.
string checkpassword = "select Password from Users where Password = '" + TextBoxPassword.Text + "'";
When checking the Password, you should also include the UserName:
string checkpassword = "select Password from Users where UserName = '" + TexBoxUserName.Text + "' AND Password = '" + TextBoxPassword.Text + "'";
If you do not include the UserName the it is only validating that some user has that password.
The following code will prevent SQL injection by paramterizing the command text
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "SELECT Count(UserName) FROM USERS WHERE UserName = #UserName";
SqlCommand com = new SqlCommand(checkuser,conn);
SqlParameter parmUserName = new SqlParameter("UserName", TextBoxUserName.Text);
com.Parameters.Add(parmUserName);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "SELECT Password FROM USERS WHERE UserName = #UserName AND Password = #Password";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
SqlParameter parmPassword = new SqlParameter("Password", TextBoxPAssword.Text);
com.Parameters.Add(parmUserName);
com.Parameters.Add(parmPassword);
string password = passComm.ExecuteScalar().ToString();

How to check if the value is not null and if not then the value should be displayed in Textbox in ASP.NET

This is my code
SqlConnection con = new SqlConnection(cs);
con.Open();
string query = "select Name from t_identities where Branchid = '" + branchidtext.Text + "' and Accountid = '" + accountidtext.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
string value = cmd.ExecuteScalar().ToString();
if (value != null)
{
nametext.Text = value.ToString();
}
else
{
nametext.Text = "No records Found";
}
}
If the query returs Null then the textbox should return No records found or else it should display the name generated by the query in the text box. Please help.
Probably you are getting error in this line
string value = cmd.ExecuteScalar().ToString();
as it trying to convert a null value to string. Better use Convert.ToString(cmd.ExecuteScalar()) to handle this case.
Your if/else block is ok
SQL's null maps to C#'s DBNull.Value:
var value = cmd.ExecuteScalar();
if (value != DBNull.Value)
{
nametext.Text = (string)value;
}
substitute
string value = cmd.ExecuteScalar().ToString();
with
object value = cmd.ExecuteScalar();
Try this:
string value = "";
if ( (value = cmd.ExecuteScalar().ToString())!= null)
{
nametext.Text=value.ToString();
}

what is wrong with this C# duplicate row code?

I'm trying to duplicate a record in my database and I used this code you see below, the sql query worked perfectly in sql server but here I don't know what the problem...help me please
//Insert new Order
int newOrderId = 0;
if (e.CommandName == "Repeat")
{
try
{
SqlConnection con = DataAccess.Connection.GetDBConnection();
//duplicate the jobs from the old order to the new added order
sqlCmd.Parameters.Clear();
string com2 = "Insert Into [OrderItems] (orderId, productId, quantity, [length], note, multipleSlip, internalDiameter, " +
"wall, machineReCuttingId,winderId, jobNote) (select #newOrderId, productId, quantity, [length], note, multipleSlip, " +
"internalDiameter, wall, machineReCuttingId, winderId, jobNote FROM OrderItems Where orderId=#oldOrderId)";
SqlCommand sqlCmd = new SqlCommand(com2, con);
sqlCmd.Parameters.Add("#newOrderId", SqlDbType.Int).Value = newOrderId;
//assign the old order Id to the insert parameter #oldOrderId
sqlCmd.Parameters.Add("#oldOrderId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument);
sqlCmd.ExecuteNonQuery();
StatusLabel.Text = "The New Order is" + newOrderId.ToString() + " The Old order ID is: " + e.CommandArgument.ToString();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
OrderGridView.DataSource = ViewDataSource(selectCustomer);
OrderGridView.DataBind();
// Response.Redirect("../Orders/AddNewOrder.aspx?customerId=" + selectCustomer + "&" + "orderId=" + newOrderId);
}
By the way I tested the values of newOrderId and the oldOrderId they are both correct

SqlException in Asp.net - Incorrect syntax near 'Van'

I have problem with my SqlCommand everything I open the page I get the error:
System.Data.SqlClient.SqlException: Incorrect syntax near 'Van'.
I cannot find the problem because 'Van' is only found once in the entire project, and in the title..
This is my code in the Page_Load:
using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")))
{
var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = " + User.Identity.Name, con);
cmd.Connection.Open();
var sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
String result = sqlReader.GetString(0);
DropDownList1.DataBind();
DropDownList1.Items.FindByValue(result).Selected = true;
//Fill some data like : string result = sqlReader("SomeFieldName");
}
sqlReader.Close();
cmd.Connection.Close();
cmd.Dispose();
}
The database connectionstring is correct because it works for all my other pages.. i'm trying to get the department where an employee works so he/she can only view memo's from their own department.
You need to close the parentheses after the last name provided.
SELECT (SELECT Memo_ID, Dep_Name FROM Department
WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName
FROM Staff WHERE (FirstName + SPACE(1) + LastName = 'xxx' )
Here is what it should look like:
using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")))
{
var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "')", con);
cmd.Connection.Open();
var sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
String result = sqlReader.GetString(0);
DropDownList1.DataBind();
DropDownList1.Items.FindByValue(result).Selected = true;
//Fill some data like : string result = sqlReader("SomeFieldName");
}
sqlReader.Close();
cmd.Connection.Close();
cmd.Dispose();
You need to quote the last name. You probably want to convert to a parameterized query too.
I'd have expected your WHERE clause to wrap the User.Identity.Name in quotes:
WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "'" ...
Could "van" be in the username?
This isn't a very secure query either - but SQL injection's another issue!

loop in select statment

protected void Button1_Click(object sender, EventArgs e)
{
if (firstname_tb.Text == "" || lastname_tb.Text == "" || email_tb.Text == "" || reemail_tb.Text == "" || pass_tb.Text == "" || gender_ddl.SelectedItem.Text == "" || day_ddl.SelectedItem.Text == "" || year_ddl.SelectedItem.Text == "")
{
Label9.Text = "please fill all data";
Label9.Visible = true;
}
else
{
str = email_tb.Text;
SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True");
SqlCommand comsel = new SqlCommand("SELECT email from reg ",con);
con.Open();
comsel.ExecuteNonQuery();
con.Close();
foreach (var v in comsel.Parameters.ToString())
{
if (v.ToString() == str)
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
b = false;
break;
}
else
{
b = true;
}
}
if (b==true)
{
birthday = day_ddl.Text + "/" + month_ddl.Text + "/" + year_ddl.Text;
SqlCommand com = new SqlCommand("INSERT INTO reg(first_name,last_name,email,email_ver,pass,gender,birthday) values(#fn,#ln,#email,#reemail,#pass,#gen,#birth)", con);
con.Open();
com.Parameters.AddWithValue("#fn", firstname_tb.Text);
com.Parameters.AddWithValue("#ln", lastname_tb.Text);
com.Parameters.AddWithValue("#email", email_tb.Text);
com.Parameters.AddWithValue("#reemail", reemail_tb.Text);
com.Parameters.AddWithValue("#pass", pass_tb.Text);
com.Parameters.AddWithValue("#gen", gender_ddl.SelectedItem.Text);
com.Parameters.AddWithValue("#birth", birthday);
com.ExecuteNonQuery();
con.Close();
Label9.Text = "thank you for registration";
Label9.Visible = true;
}
else
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
}
}
There is a problem that is when I try to enter email allready exist in the database it enterd while it must show to the user that this email already exist in the data base. Can any one help me?
OK as far as I can understand, you only want the INSERT to occur if the email is unique in the [reg].[email] field. This will happen if b == true. The logic you use for this is basically correct, but you are not retrieving the results of the database correctly. Try something like:
con.Open();
System.Data.SqlClient.SqlDataReader objReader = comsel.ExecuteReader();
while (objReader.Read())
{
if ((String)objReader("email") == str)
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
b = false;
break;
}
else
{
b = true;
}
}
con.Close();
Hopefully that will work as intended.
On a side note, I would be remiss not to mention that this approach is pretty inefficient. A better idea would be to use a query like this:
SELECT [email] FROM [reg] WHERE [email] = #email;
In which you specify your variable "str" as a parameter in a similar manner to the INSERT operation below. Then instead of iterating through the results, simply check to see if the SqlDataReader has any rows:
SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True");
SqlCommand comsel = new SqlCommand("SELECT [email] FROM [reg] WHERE [email] = #email;",con);
comsel.Parameters.AddWithValue("#email", str);
System.Data.SqlClient.SqlDataReader objReader = comsel.ExecuteReader();
if (objReader.HasRows())
{
b = false;
}
else
{
b = true;
}
con.Close();
Remove the if statement checking for field entries and add RequiredValidators to your form:
https://web.archive.org/web/20211020145950/https://www.4guysfromrolla.com/webtech/090200-1.shtml
As for the second part.. if email already exists... create a custom validator for this and use this to display the message to your user if the email already exists. Note that you're using ExecuteNonQuery() here for what is essentially a query...
You also need some "separation of concerns". For example, put the connection string in the Web.Config. Do your data access from a DAL class, etc
For the first query, you can just use ExecuteScalar as that will return a single value from your query. I rewrote your query so that it will do a count of the emails that match the email the user is trying to use. If the count returned is 0, then you know that the email is currently not in use.
string strEmail = email_tb.Text.Trim();
try
{
using(SqlConnection conn = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT COUNT(1) FROM reg WHERE email = #email", conn);
cmd.Parameters.AddWithValue("#email", strEmail);
int count = (int)cmd.ExecuteScalar();
if(count==0)
{
birthday = day_ddl.Text + "/" + month_ddl.Text + "/" + year_ddl.Text;
SqlCommand cmdInsert = new SqlCommand("INSERT INTO reg(first_name,last_name,email,email_ver,pass,gender,birthday) values(#fn,#ln,#email,#reemail,#pass,#gen,#birth)", conn);
cmdInsert.Parameters.AddWithValue("#fn", firstname_tb.Text);
cmdInsert.Parameters.AddWithValue("#ln", lastname_tb.Text);
cmdInsert.Parameters.AddWithValue("#email", email_tb.Text);
cmdInsert.Parameters.AddWithValue("#reemail", reemail_tb.Text);
cmdInsert.Parameters.AddWithValue("#pass", pass_tb.Text);
cmdInsert.Parameters.AddWithValue("#gen", gender_ddl.SelectedItem.Text);
cmdInsert.Parameters.AddWithValue("#birth", birthday);
cmdInsert.ExecuteNonQuery();
Label9.Text = "thank you for registration";
Label9.Visible = true;
}
else
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
}
}
}
catch(SqlException ex)
{
// log your exception then display a friendly message to user
Label9.Text = "An error occurred while trying to save your registration";
}

Resources