This is my code used for updating a customer in c#, can someone help me correcting the code, so that it will work smoothly?
This is my repository code:
public static void KlantWijzigen(Klant klan)
{
string commandString = string.Format("UPDATE tblKlanten (Adres, Postcode, Gemeente, Email, Telefoonnummer) SET('{0}','{1}','{2}','{3}','{4}')", klan.Adres, klan.Postcode, klan.Gemeente, klan.Email, klan.Telefoonnummer);
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand command = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
conn.Open();
//commandstring toevoegen aan adapter
command.Connection = conn;
command.CommandText = commandString;
adapter.UpdateCommand = command;
//command uitvoeren
adapter.UpdateCommand.ExecuteNonQuery();
//databank connect
conn.Close();
}
My new window code:
public partial class WindowKlantWijzig : Window
{
public WindowKlantWijzig()
{
InitializeComponent();
}
private void buttonSlaOp_Click(object sender, RoutedEventArgs e)
{
Klant upda = new Klant();
upda.Naam = textBoxNieuweNaam.Text;
upda.Adres = textBoxAdresNieuw.Text;
upda.Postcode = Convert.ToInt32(textBoxPostcodeNieuw.Text);
upda.Gemeente = textBoxGemeenteNieuw.Text;
upda.Email = textBoxEmailNieuw.Text;
upda.Telefoonnummer = textBoxTelefoonnummerNieuw.Text;
KlantRepository.KlantWijzigen(upda);
MessageBox.Show("De klant werd succesvol gewijzigd");
}
}
And this is my main window code
private void buttonWijzigKlant_Click(object sender, RoutedEventArgs e)
{
if (comboBoxKlanten.SelectedIndex == -1)
{
MessageBox.Show("Selecteer de klant die je wil wijzigen");
}
else
{
// TODO: gebruiker eerst om bevestiging vragen
Klant klan = (Klant)comboBoxKlanten.SelectedItem;
KlantRepository.KlantWijzigen(klan);
MessageBox.Show("De klant werd succesvol gewijzigd");
//combobox wordt vernieuwd
comboBoxKlanten.ItemsSource = null;
comboBoxKlanten.ItemsSource = KlantRepository.AlleKlanten();
}
}
As response on the question from the comments, I would do it like this: (untested/pseudo) So this is NOT the answer, but a response to prevent SQL-injections.
public static void KlantWijzigen(Klant klan)
{
string commandString = "UPDATE tblKlanten (Adres, Postcode, Gemeente, Email, Telefoonnummer) SET(#Adres, #Postcode, #Gemeente, #Email, #Telefoonnummer)";
using(OleDbConnection conn = new OleDbConnection(connectionString))
using(OleDbCommand command = new OleDbCommand())
{
conn.Open();
//commandstring toevoegen aan adapter
command.Connection = conn;
command.CommandText = commandString;
// de velden zetten via de parameters, zodat SQL-injection niet werkt.
command.Parameters.Add("Adres", OleDbType.VarChar).Value = klan.Adres;
command.Parameters.Add("Postcode", OleDbType.VarChar).Value = klan.Postcode;
command.Parameters.Add("Gemeente", OleDbType.VarChar).Value = klan.Gemeente;
command.Parameters.Add("Email", OleDbType.VarChar).Value = klan.Email;
command.Parameters.Add("Telefoonnummer", OleDbType.VarChar).Value = klan.Telefoonnummer;
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.UpdateCommand = command;
//command uitvoeren
adapter.UpdateCommand.ExecuteNonQuery();
}
}
Don't forget... you're missing a Where clause.. so you are updating ALL records.
You might change (something like):
string commandString = #"
UPDATE tblKlanten (Adres, Postcode, Gemeente, Email, Telefoonnummer)
SET(#Adres, #Postcode, #Gemeente, #Email, #Telefoonnummer)
WHERE id = #Id"; // <<--------------
command.Parameters.Add("Id", OleDbType.Integer).Value = klan.Id;
Related
so I have this refresh and populate function here
private void Refresh()
{
MySqlCommand cmd = conn.CreateCommand();
String data, id, platenumber, brand, model, yearmodel, odometer;
cmd.CommandText = "SELECT * FROM vehicle";
cmd.CommandType = CommandType.Text;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
id = reader.GetInt32(0).ToString();
platenumber = reader.GetString(1);
brand = reader.GetString(2);
data = $"{ id}/{ platenumber}/{ brand}";
}
reader.Close();
PopulateDataGrid();
}
private void PopulateDataGrid()
{
Form1 f1 = new Form1();
MySqlCommand cmd = conn.CreateCommand();
DataTable datatable = new DataTable();
cmd.CommandText = "select id,platenumber,brand,model,yearmodel,regdate,exdate,odometer from vehicle";
cmd.CommandType = CommandType.Text;
dataAdapter = new MySqlDataAdapter(cmd);
dataAdapter.Fill(datatable);
f1.dataGridView1.DataSource = datatable;
}
and this is my update function
private void savebtn_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
int newid = Convert.ToInt32(idtxt.Text);
int ID = newid;
MySqlCommand cmd = new MySqlCommand("update vehicle set platenumber=#platenumber where ID = #id" , conn);
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.Add("#platenumber", MySqlDbType.VarChar, 10).Value = pnumber.Text;
cmd.Parameters.Add("#brand", MySqlDbType.VarChar, 60).Value = brand.Text;
cmd.Parameters.Add("#model", MySqlDbType.VarChar, 45).Value = model.Text;
cmd.Parameters.Add("#yearmodel", MySqlDbType.Int32).Value = yearmodel.Text;
//cmd.Parameters.Add("#regdate", MySqlDbType.Date).Value = datereg.MinDate;
//cmd.Parameters.Add("#exdate", MySqlDbType.Date).Value = regexp.MinDate;
cmd.Parameters.Add("#odometer", MySqlDbType.Decimal).Value = odometer.Text;
int i = cmd.ExecuteNonQuery();
if (i != 0)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Fail");
}
f1.Refresh();
this.Close();
}
the problem is when I click on the save button on FORM2 everything on the datagrid stays the same but when I click a refresh button from FORM1 with the same code it works. even if I put the function in FORM2 it still doesn't refresh the datagrid after I click the update button. what am I missing here?
enter image description hereI am writing the update query but it doesn't work. When I run this code, nothing is updated in my database table.
My connection string is
public partial class cutomers : Form
{
public static string connection =
#"Data Source=HOME-PC\SQLEXPRESS;Initial Catalog=WATER-Supply;Integrated Security=True";
SqlConnection con = new SqlConnection(connection);
private void update_Click(object sender, EventArgs e)
{
con.Open();
string UPDATE = "UPDATE Customer_db SET Cust_Phone = #cusphone, Cust_Email = #cusemail, Cust_Address = #cusaddress WHERE Cust_Name = #cusname";
SqlCommand cmd = new SqlCommand(UPDATE, con);
cmd.Parameters.AddWithValue("#cusname", cusname.Text);
cmd.Parameters.AddWithValue("#cusphone", cusphone.Text);
cmd.Parameters.AddWithValue("#cusemail", cusemail.Text);
cmd.Parameters.AddWithValue("#cusaddress", cusaddress.Text);
int i = cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Customer Update...");
}
}
I created a console application and I was able to update with the following code. What is the value returned by: command.ExecuteNonQuery()?
class Program
{
static void Main(string[] args)
{
UpdateCustomerCommand(Guid.Parse("77ceef70-ab98-4392-835d-66c9face5f16"), "John Doe", "johndoe#acme.com");
}
public static string connectionString = #"Data Source=localhost\SQLEXPRESS;Initial Catalog=labdb;Integrated Security=True;Pooling=False";
private static void UpdateCustomerCommand(Guid Id, string name, string email)
{
var updateCommand = "UPDATE [Customer] SET [Name] = #NAME, [EMAIL] = #EMAIL WHERE [Id] = #ID";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(updateCommand, connection);
command.Parameters.Add("#ID", SqlDbType.UniqueIdentifier);
command.Parameters["#ID"].Value = Id;
command.Parameters.Add("#NAME", SqlDbType.NVarChar, 150);
command.Parameters["#NAME"].Value = name;
command.Parameters.Add("#EMAIL", SqlDbType.NVarChar, 100);
command.Parameters["#EMAIL"].Value = email;
command.Connection.Open();
command.ExecuteNonQuery();
}
}
I am a newbie.
I am attempting to check for duplicate database entries. My problem is:
I would like a success alert shown if the entry is successful.
A notification of duplicates shown if a duplicate exists.
My issue is: the alert for duplicates gets shown multiple times, however, the entry is never created if no duplicates exist.
This is my code:
/// <summary>
/// The following procedure creates the user account in the database The procedure first attempts to
/// perform a check for duplicates before submitting the registration info
/// </summary>
protected void BTN_CreateACNT_Click(object sender, EventArgs e)
{
string InsertQuery = "";
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Reimburse"].ConnectionString;
InsertQuery = "Insert into TBL_Logins (FirstName, LastName, EmailAddress, Password) VALUES(#FirstName, #LastName, #EmailAddress, #Password)";
String FirstNameSTR = FN.Text.Trim();
String LastNameSTR = LN.Text.Trim();
String EMailAddressSTR = EmailAddress.Text.Trim();
byte[] PassByte = StrToByteArray(PWD.Text.Trim());
// CheckUser(EMailAddressSTR);
while (CheckUser(EMailAddressSTR) == false)
{
SqlConnection CN = new SqlConnection(ConnectionString);
SqlCommand CMD = new SqlCommand(InsertQuery, CN);
CMD.CommandType = CommandType.Text;
CMD.Parameters.AddWithValue("#Firstname", FirstNameSTR);
CMD.Parameters.AddWithValue("#LastName", LastNameSTR);
CMD.Parameters.AddWithValue("#EmailAddress", EMailAddressSTR);
CMD.Parameters.AddWithValue("#Password", PassByte);
CN.Open();
CMD.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('Account created successfully.');</script>");
CN.Close();
}
}
public bool CheckUser(String UserString)
{
String UserSelect = "Select * from TBL_Logins where EmailAddress = #EmailAddress";
int MailCount = 0;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Reimburse"].ConnectionString;
SqlConnection CN = new SqlConnection(ConnectionString);
UserString = EmailAddress.Text.Trim();
SqlCommand CMD = new SqlCommand(UserSelect, CN);
CMD.Parameters.AddWithValue("#EmailAddress", UserString);
CN.Open();
SqlDataReader dr = CMD.ExecuteReader();
while (dr.Read())
{
if (UserString == dr["EmailAddress"].ToString())
{
Response.Write("<script language='javascript'>alert('This EMail address is already taken. Please try again.');</script>");
// return true;
}
}
CN.Close();
return true;
}
protected void BTN_CreateACNT_Click(object sender, EventArgs e)
{
string InsertQuery = "";
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Reimburse"].ConnectionString;
InsertQuery = "Insert into TBL_Logins (FirstName, LastName, EmailAddress, Password) VALUES(#FirstName, #LastName, #EmailAddress, #Password)";
String FirstNameSTR = FN.Text.Trim();
String LastNameSTR = LN.Text.Trim();
String EMailAddressSTR = EmailAddress.Text.Trim();
byte[] PassByte = StrToByteArray(PWD.Text.Trim());
// CheckUser(EMailAddressSTR);
while(CheckUser(EMailAddressSTR) == false)
{
SqlConnection CN = new SqlConnection(ConnectionString);
SqlCommand CMD = new SqlCommand(InsertQuery, CN);
CMD.CommandType = CommandType.Text;
CMD.Parameters.AddWithValue("#Firstname", FirstNameSTR);
CMD.Parameters.AddWithValue("#LastName", LastNameSTR);
CMD.Parameters.AddWithValue("#EmailAddress", EMailAddressSTR);
CMD.Parameters.AddWithValue("#Password", PassByte);
CN.Open();
CMD.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('Account created successfully.');</script>");
CN.Close();
}
}
public bool CheckUser(String UserString)
{
String UserSelect = "Select * from TBL_Logins where EmailAddress = #EmailAddress";
int MailCount = 0;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Reimburse"].ConnectionString;
SqlConnection CN = new SqlConnection(ConnectionString);
UserString = EmailAddress.Text.Trim();
SqlCommand CMD = new SqlCommand(UserSelect,CN);
CMD.Parameters.AddWithValue("#EmailAddress", UserString);
CN.Open();
SqlDataReader dr = CMD.ExecuteReader();
while (dr.Read())
{
if (UserString == dr["EmailAddress"].ToString())
{
Response.Write("<script language='javascript'>alert('This EMail address is already taken. Please try again.');</script>");
// return true;
}
}
CN.Close();
return true;
}
Looks like the CheckUser method always returns true and that's why the insertion does not work, update the method to return false by default:
while (dr.Read())
{
if (UserString == dr["EmailAddress"].ToString())
{
Response.Write("<script language='javascript'>alert('This EMail address is already taken. Please try again.');</script>");
return true; // return true if user exists
}
}
CN.Close();
return false; // return false if the user does not exist
It is also recommended to use using block to dispose the DB connection instead of manually invoking the Close() method.
public void make_new_order(IorderBO order)
{
int id;
using (SqlConnection con = DButility.getconnection())
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "placeorder";
com.Parameters.AddWithValue("#Customer_name", order.Customer_name);
com.Parameters.AddWithValue("#Email_id", order.Email_id);
com.Parameters.AddWithValue("#Phone_number", order.Phone_number);
com.Parameters.AddWithValue("#Required_quantity", order.Required_quantity);
com.Parameters.AddWithValue("#Product_id", order.Product_id);
int row_affected = com.ExecuteNonQuery();
if(row_affected>0)
{
HttpContext.Current.Response.Write("<script>alert('Order placed Sucessfully!!')</script>");
string s = "select max(Order_id) from manchester";
SqlCommand c = new SqlCommand(s, con);
id = (int)c.ExecuteScalar();
HttpContext.Current.Response.Write("<script>alert('Please note your Order-Id:" + id + "')</script>");
}
con.Close();
}
}
public List<IorderBO> view_all_order()
{
using(SqlConnection con = DButility.getconnection())
{
List<IorderBO> list_of_order = new List<IorderBO>();
SqlCommand com = new SqlCommand();
com.Connection = con;
con.Open();
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "see";
SqlDataReader r = com.ExecuteReader();
while(r.Read())
{
int id = Convert.ToInt16(r["Order_id"].ToString());
int pid = Convert.ToInt16(r["Product_id"].ToString());
int re = Convert.ToInt16(r["Required_quantity"].ToString());
string n = r["Customer_name"].ToString();
string e = r["Email_id"].ToString();
Int64 p = Convert.ToInt64(r["Phone_number"].ToString());
IorderBO or = new orderBO(id, pid, re, n, e, p);
list_of_order.Add(or);
}
con.Close();
return list_of_order;
}
}
public DataTable searchby_id(int id)
{
using (SqlConnection con = DButility.getconnection())
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "seestat";
com.Parameters.AddWithValue("#Product_id", id);
DataTable d = new DataTable();
SqlDataReader r = com.ExecuteReader();
d.Load(r);
return d;
//con.Close();
}
}
Even the grid view event is not working
protected void Page_Load(object sender, EventArgs e)
{
List<IorderBO> list_order = new List<IorderBO>();
list_order = o.view_all_order();
GridView1.DataSource = list_order;
GridView1.DataBind();
}
create procedure placeorder
(#Product_id int ,
#Required_quantity int ,
#Customer_name varchar(50),
#Email_id varchar(30),
#Phone_number bigint)
as
begin
insert into manchester values(#Product_id,#Required_quantity,#Customer_name,#Email_id,#Phone_number)
end
create procedure see
as
begin
select * from manchester
end
exec see
declare #Product_id int
create procedure seestat(#Product_id int)
as
begin
select count(Product_id) As Number_of_Orders from manchester where (Product_id=#Product_id)
end
I already could make the password to become not stored as the original text in the database. But while I want to retrieve it and check between the entered password with in the database, the error appears
Value cannot be null
on this line of code:
string verifyHashedPassword = Convert.ToString(Crypto.VerifyHashedPassword(_registration.hashedPassword, this.textBox2.Text));
Here is the code that I am using for Login:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
Registration _registration = new Registration();
private void CheckUserDatabase(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT [Username], [Password], [UserType], [UserStore] FROM [Member] WHERE [Username] = #Username AND [Password] = #Password";
string verifyHashedPassword = Convert.ToString(Crypto.VerifyHashedPassword(_registration.hashedPassword, this.textBox2.Text));
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = verifyHashedPassword;
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
if (dReader.Read())
{
UserInformation.CurrentLoggedInUser = (string)dReader["Username"];
UserInformation.CurrentLoggedInUserType = (string)dReader["UserType"];
UserInformation.CurrentLoggedInUserStore = (string)dReader["UserStore"];
}
else
{
RecursiveClearTextBoxes(this.Controls);
}
dReader.Close();
conn.Close();
}
}
}
}
Here is the code for Registration:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
private void AddDatabase(object sender, EventArgs e)
{
string query = "INSERT INTO [Member] ([Username], [Password], [UserType], [UserStore]) VALUES (#Username, #Password, #UserType, #UserStore)";
string hashedPassword = Crypto.HashPassword(this.textBox2.Text);
OleDbConnection _conn = new OleDbConnection(connectionString);
_conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, _conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = hashedPassword;
cmd.Parameters.Add("#UserType", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserType"].Value = this.textBox3.Text;
cmd.Parameters.Add("#UserStore", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserStore"].Value = this.textBox4.Text;
cmd.ExecuteNonQuery();
DialogResult _dialogResult = MessageBox.Show("Added Successfully", "Success", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
this.Hide();
this.Close();
}
}
}
}
Any help?
Your answer much appreciated!
Thank you