Users can edit their profiles as shown in Figure 22.7. The code for this page can be seen in Listing 22.11. Listing 22.11 This Code Is Behind the EditProfile.aspx Page.// This method is executed when the page first loads. private void Page_Load(object sender, System.EventArgs e) { if( !IsPostBack ) { // Create a connection object. SqlConnection objConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectString"]); SqlDataReader objReader = null; try { // Open the connection. objConnection.Open(); // Create a command object. SqlCommand objCommand = new SqlCommand( "select Password,Email,DateOfBirth from " + "Users where ID='" + Convert.ToString( Session["ID"] ) + "'", objConnection ); objReader = objCommand.ExecuteReader(); if( objReader.Read() ) { Name.Text = Convert.ToString( Session["Name"] ); Password.Text = Convert.ToString( objReader["Password"] ); Email.Text = Convert.ToString( objReader["Email"] ); DateOfBirth.Text = Convert.ToDateTime( objReader["DateOfBirth"] ).ToShortDateString(); } else { ErrorMessage.Text = "Could not retrieve user record."; } } catch( Exception ex ) { // Alert the user to the error. ErrorMessage.Text = ex.Message.ToString(); } finally { if( objReader != null ) { objReader.Close(); } // Close the connection. if( objConnection.State == ConnectionState.Open ) { objConnection.Close(); } } } } private void Update_Click(object sender, System.EventArgs e) { // Create a connection object. SqlConnection objConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectString"]); try { Session["Name"] = Name.Text.Trim().ToUpper(); // Open the connection. objConnection.Open(); // Create a command object. SqlCommand objCommand = new SqlCommand( "Update Users set Name='" + Convert.ToString( Session["Name"] ) + "',Password='" + Password.Text.Trim().ToUpper() + "',Email='" + Email.Text.Trim() + "',DateOfBirth='" + DateOfBirth.Text.Trim()+ "' where ID"] ), objConnection ); objCommand.ExecuteNonQuery(); ErrorMessage.Text = "Your profile has been updated."; Update.Visible = false; Cancel.Text = " OK "; } catch( Exception ex ) { // Alert the user to the error. ErrorMessage.Text = ex.Message.ToString(); } finally { // Close the connection. if( objConnection.State == ConnectionState.Open ) { objConnection.Close(); } } } private void Cancel_Click(object sender, System.EventArgs e) { Response.Redirect( "Default.aspx" ); } Figure 22.7. You Can Edit Your User Profile Even After You've Created a Login. |