edit the values of a database row that are displayed in textboxes - sql

New to WPF. I want to edit the values of a database row that are displayed in textboxes. At the moment I am getting an error: "ExecuteNonQuery:Connection property has not been initialized". When I remove the where clause all rows are updated and not just the selected item.
private void btnEDIT_Click(object sender, RoutedEventArgs e)
{
try
{
sc.Open();
cmd = new SqlCommand("Update Rewards set Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'where Name = '" + this.txtName.Text +"'");
cmd.ExecuteNonQuery();
MessageBox.Show("Update Successfull");
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

You haven't set the Connection property of SqlCommand. So the command does not know where to connect. Use the constructor overload from SqlCommand or set it separate like this
cmd.Connection = sc;

cmd = new SqlCommand("Update Rewards set Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'where Name = '" + this.txtName.Text +"'",sc); // add connection here
also You should use parametrized queries or Stored Procedures that will prevent SQL Injection attacks.
SqlCommand cmd = new SqlCommand("Update Rewards set Name = #name, Cost= #cost where Name = #name ,sc);
cmd.Parameters.AddWithValue("#name", Convert.ToString(this.txtName.Text)); and so on

I hope this is what you need :) Copy paste this. Good luck bro! :) If you have question, just ask, I'll answer if I know LOL :)
private void btnEDIT_Click(object sender, RoutedEventArgs e)
{
try
{
sc.Open();
sql = "UPDATE REWARDS SET Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'WHERE Name = '" + this.txtName.Text +"'");
SqlCommand command = new SqlCommand(sql, con);
command.ExecuteNonQuery();
MessageBox.Show("Update Successfull");
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Related

Syntax Error in INSERT INTO Statement (Insert Records)

can someone help me what is wrong with my code? It always says "Syntax error in INSERT INTO statement. "
try
{
OleDbConnection Con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\MotoFix.mdb;");
Con.Open();
OleDbCommand Com = new OleDbCommand();
Com.Connection = Con;
Com.CommandText = "INSERT INTO Order VALUES ('" + txtRandomOrder.Text + "','" + txtCode.Text + "')";
Com.ExecuteNonQuery();
Con.Close();
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message);
}
Order is a keyword in msaccess refer this link
http://office.microsoft.com/en-us/access-help/access-2007-reserved-words-and-symbols-HA010030643.aspx
change your statement to
"INSERT INTO [Order] VALUES ('" + txtRandomOrder.Text + "','" + txtCode.Text + "')";
and see if it works

c# - SqlReader of Read() not working

Problem: SqlReader of Read() not working
User Action:
enter their ID in a textbox and click a button
Program Action:
Select their name from database by given ID value
Then Print their name with HI! Message in RichTextBox or in Textbox
Error List:
No Error
Database:
Schema - dbo
Name - Sheet#Attendance
Here is my code:
private void swipe_button_Click(object sender, EventArgs e)
{
String ID_givenbyUSER = IDtxtBox.Text;
SqlConnection sqlConn = null;
sqlConn = new SqlConnection("Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=ABC_SchoolDB;Integrated Security=True");
sqlConn.Open();
SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet#Attendance where Serial_Id=" + " ' " + ID_givenbyUSER + " ' ", sqlConn);
SqlDataReader sqlReader = cmd.ExecuteReader();
richTxtBox.Clear();
richTxtBox.AppendText("Hi buddy "); //This line works
while (sqlReader.Read())
{
richTxtBox.AppendText("Hi buddy "); //But,Its not work
pwdbox.Text = (sqlReader["Student_Name"].ToString()); //Its not work too
}
if (sqlConn != null)
{
sqlConn.Close();
sqlConn = null;
}
}
}
I think your problem is here:
SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet#Attendance where Serial_Id=" + " ' " + ID_givenbyUSER + " ' ", sqlConn);
try this instead:
SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet#Attendance where Serial_Id='" + ID_givenbyUSER + "'", sqlConn);
Notice the part where you concatenate the single-quotes? It had spaces around them so your query would look like:
Where Serial_Id= ' Name '
The space in front of the user supplied value was probably causing your query to not return any rows.

Error with SQL command

I'm trying to get the users details in the text boxes in my form to my database in access, which should save. However i keep getting an error message every time i click to register, the following code is how i am trying to write it out:
public void AddNewUser()
{
string filePath;
try
{
filePath = (Application.StartupPath + ("\\" + DBFile));
connection = new System.Data.OleDb.OleDbConnection((ConnectionString + filePath));
connection.Open();
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text +("\', "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
connection.Close();
}
}
However I think that the problem is actually coming from this section:
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text +("\', "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
Really your query is unreadable. Any kind of error could hide in that jungle of string concatenation and single quotes sprawled everywhere. (like a not necessary comma escaped probably from a fixup of a copy/paste operation)
You should use parameterized query and all of this will disappear
command.Connection = connection;
string sql = "UPDATE enroll SET SSN=?, Name=?, Company=? WHERE ID=?";
command.CommandText = sql;
command.Parameters.AddWithValue("#p1", txtSSN.Text);
command.Parameters.AddWithValue("#p2", txtName.Text );
command.Parameters.AddWithValue("#p3", txtCompany.Text);
command.Parameters.AddWithValue("#p4", _UserID);
command.ExecuteNonQuery();
Now I think that this is really more readable, no quotes to add because the framework knows the datatype of every parameter and will use the appropriate quoting required. Last but not least, no problem with Sql Injection

Error Number of query values and destination fields are not the same

I have a problem when I run my code "without YearlyLimit" then it is run properly but when i add the YearlyLimit in insert query then error occurs
"Number of query values and destination fields are not the same."
protected void btn_Save_Click(object sender, EventArgs e)
{
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Geeta/Desktop/eTimeTrackLite1.mdb;Persist Security Info=False;");
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string query = "insert into LeaveTypes (LeaveTypeFName,LeaveTypeSName,YearlyLimit,Gender) values ('" + txt_leavetypename.Text + "', '" + txt_shortname.Text + "', '" + txt_yearlimit.Text + "', '" + Convert.ToString(rdbtn_all.Checked) + "', '" + Convert.ToString(rdbtn_male.Checked) + "', '" + Convert.ToString(rdbtn_female.Checked) + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.ExecuteNonQuery();
conn.Close();
BindGridData();
}
You are trying to add too many items into the record
LeaveTypeFName
LeaveTypeSName
YearlyLimit
Gender
You are trying to insert
txt_leavetypename.Text
txt_shortname.Text
txt_yearlimit.Text
Convert.ToString(rdbtn_all.Checked)
Convert.ToString(rdbtn_male.Checked)
Convert.ToString(rdbtn_female.Checked)
you need to make a check on which item you want to go into the last field

Exception while retrieve a null field from sql ce 3.5

I am storing an image in a table in varbinary(max) format, actually first time it will be empty, I am checking whether it is empty of not but while checking for null field I am getting any exception stating invalid cast so can any one suggest what is the problem with this.
code sample is
con = new SqlCeConnection(CommonClass.ConnectionStringStartup);
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT Signature,UserId FROM UserMaster Where " +
" LoginName = '" + UserName + "' " +
" AND Password = '" + Password + "'";
cmd.CommandType = CommandType.Text;
// MessageBox.Show(UserName);
SqlCeDataReader dr;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read())
{
if (dr.IsDBNull(0))
SignLoaded = false;
else
SignLoaded = true;
}
Thanks in advance
With regards
Bharath kumar
To me, it looks like this should work?
Have you tried Convert.IsDbNull( dr.GetValue(0))?
Otherwise I can only suggest using dr.GetValue(0) and look at the result.
Cheers