private void button1_Click(object sender, EventArgs e) { try { c_CurrentUser = c_DB.NewUser(FirstNameTextBox.Text, LastNameTextBox.Text, short.Parse(AgeTextBox.Text), StatusTextBox.Text); } catch (SqlException ex) { MessageBox.Show(ex.Message); return; } bindingSource1.DataSource = c_CurrentUser; c_Memento = new Memento(c_CurrentUser); c_Memento.Save(); }
public SimpleUser NewUser(string firstName, string lastName, short age, string status) { SimpleUser newUser = null; string strSql = "INSERT INTO EXP.SimpleUser (FirstName, LastName, Age, Status, LastUpdate) " + "VALUES (@FirstName, @LastName, @Age, @Status, GETDATE()) " + "SELECT @ID = ID, @LastUpdate = LastUpdate FROM EXP.SimpleUser WHERE ID = @@IDENTITY"; //****without using Stored procedure: incase of we need multiple value using (SqlConnection con = new SqlConnection(c_ConnectionString)) using (SqlCommand cmd = con.CreateCommand()) { cmd.CommandText = strSql; cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = firstName; cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 50).Value = lastName; cmd.Parameters.Add("@Age", SqlDbType.SmallInt).Value = age; cmd.Parameters.Add("@Status", SqlDbType.VarChar, 50).Value = status; cmd.Parameters.Add("@ID", SqlDbType.Int).Direction = ParameterDirection.Output; cmd.Parameters.Add("@LastUpdate", SqlDbType.DateTime).Direction = ParameterDirection.Output; con.Open(); int affectedRow = cmd.ExecuteNonQuery(); if (affectedRow == 1) { newUser = new SimpleUser() { FirstName = firstName, LastName = lastName, Age = age, Status = status, ID = (int)cmd.Parameters["@ID"].Value, LastUpdate = (DateTime)cmd.Parameters["@LastUpdate"].Value }; } } return(newUser); }
public Memento(SimpleUser source) { c_Source = source; c_Backup = new SimpleUser(); }