Prince Sultan University College of Computer & Information Sciences Department of Computer Science CS371: Web Development Practice Sheet 6 TableModification and Updating Using a Grid Using this worksheet you will learn how to modify and update database tables through a grid control. The grid control is bound to the database table and provides command columns to edit and update tables. To insert information in the table, the user is provided with a set of textboxes to enter the required information. An Insert Button Click event is programmed to insert a new row in the table (including the information entered by the user) The Data Tier: Create the following stored procedures in your Database: Insert a new category in your Categories table: Note the use of parameters this time. CREATE PROCEDURE InsertCategory (@CategoryNameVARCHAR(50), @CategoryDescriptionVARCHAR(50)) AS INSERT INTO Categories (Name, Description) VALUES (@CategoryName, @CategoryDescription) RETURN Update a category in your Categories table: Again note the use of parameters CREATE PROCEDURE UpdateCategory (@CategoryIDINT, @CategoryNameVARCHAR(50), @CategoryDescriptionVARCHAR(1000)) AS UPDATE Categories SET Name = @CategoryName, Description = @CategoryDescription WHERE ID = @CategoryID RETURN Delete a category from the table: CREATE PROCEDURE DeleteCategory (@CategoryIDINT) AS DELETE FROM Categories WHERE ID = @CategoryID RETURN 1 Retrieve information from the table: CREATE PROCEDURE GetCategory AS selectID, Name, Description from Categories RETURN The Presentation Tier: Create the following controls on your form: Note that last two columns in the grid are command columns that are added as follows: 2 The Business Tier: Add the following declarations at the beginning of the class: int CGID; stringCGName, CGDes; //Category name and description // Instantiate the connection SqlConnection conn; 3 Create a Connection Object and Bind the grid to the table in the Page_Load() method: protectedvoidPage_Load(object sender, EventArgs e) { conn = newSqlConnection("Data Source=(local);Initial Catalog=MyShop;Integrated Security=SSPI"); statusLabel.Text = conn.State.ToString(); // Load the grid only the first time the page is loaded if (!Page.IsPostBack) { // Load the departments grid BindGrid(); // Set control properties statusLabel.ForeColor = System.Drawing.Color.Red; } } Where BindGrid() is implemented as follows: // Populate the GridView with data privatevoidBindGrid() { // Get a DataTable object containing the catalog departments Grid.DataSource = GetCategories(); // Bind the data bound controls to the data source Grid.DataBind(); } And the GetCategries Method is implemented as follows: privateDataTableGetCategories() { SqlDataReaderrdr = null; DataTable table; try { // 1. Instantiate a new command with a query and connection SqlCommandcmd = newSqlCommand("GetCategory", conn); cmd.CommandType = CommandType.StoredProcedure; // Open the connection if (conn.State.ToString() == "Closed") conn.Open(); // 2. Call Execute reader to get query results rdr = cmd.ExecuteReader(); table = newDataTable(); table.Load(rdr); 4 return table; } finally { // close the reader if (rdr != null) { rdr.Close(); } // Close the connection if (conn != null) { conn.Close(); } } } Implement the InsertCategory method as follows: //Insert Data in Table publicvoidInsertCategory(stringCatName, stringCatDescription) { try { // 1. Instantiate a new command with a query and connection SqlCommandcmd = newSqlCommand("InsertCategory", conn); cmd.CommandType = CommandType.StoredProcedure; // 2. define parameters used in command object SqlParameterparam = newSqlParameter(); param.ParameterName = "@CategoryName"; param.Value = CatName; // 3. add new parameter to command object cmd.Parameters.Add(param); param = cmd.CreateParameter(); param.ParameterName = "@CategoryDescription"; param.Value = CatDescription; // 3. add new parameter to command object cmd.Parameters.Add(param); // Open the connection conn.Open(); // 2. Call ExecuteNonQuery to send command cmd.ExecuteNonQuery(); BindGrid(); } finally { 5 // Close the connection if (conn != null) { conn.Close(); } } } Implement the UPdateCategory Method as follows: //Update Category Table privateboolUpdateCategory(stringCatID, stringCatName, stringCatDescription) { try { // Open the connection conn.Open(); // 1. Instantiate a new command with command text only SqlCommandcmd = newSqlCommand("UpdateCategory"); cmd.CommandType = CommandType.StoredProcedure; // 2. Set the Connection property cmd.Connection = conn; SqlParameterparam = newSqlParameter(); param.ParameterName = "@CategoryID"; param.Value = CatID; // 3. add new parameter to command object cmd.Parameters.Add(param); param = cmd.CreateParameter(); param.ParameterName = "@CategoryName"; param.Value = CatName; // 3. add new parameter to command object cmd.Parameters.Add(param); param = cmd.CreateParameter(); param.ParameterName = "@CategoryDescription"; param.Value = CatDescription; // 3. add new parameter to command object cmd.Parameters.Add(param); // 3. Call ExecuteNonQuery to send command int result; result= cmd.ExecuteNonQuery(); BindGrid(); return (result != -1); } finally { // Close the connection if (conn != null) 6 { conn.Close(); } } } Implement the Delete Category Method as follows: //Delete Data from table publicboolDeleteCategory(stringCatID) { try { // Open the connection conn.Open(); // 1. Instantiate a new command SqlCommandcmd = newSqlCommand(); // 2. Set the CommandText property cmd.CommandText = "DeleteCategory"; cmd.CommandType = CommandType.StoredProcedure; // 3. Set the Connection property cmd.Connection = conn; SqlParameterparam = newSqlParameter(); param.ParameterName = "@CategoryID"; param.Value = CatID; // 3. add new parameter to command object cmd.Parameters.Add(param); // 4. Call ExecuteNonQuery to send command int result = -1; result= cmd.ExecuteNonQuery(); BindGrid(); conn.Close(); return (result != -1); } finally { // Close the connection if (conn != null) { conn.Close(); } } } Back to the Presentation Tier: 7 Implement the Insert Button Click event as follows: protectedvoidbtnInsert_Click(object sender, EventArgs e) { CGName = txtName.Text; CGDes = txtDes.Text; InsertCategory(CGName, CGDes); BindGrid(); } Implement the major Grid events as follows: The RowEditing Event: protectedvoidGrid_RowEditing(object sender, GridViewEditEventArgs e) { // Set the row for which to enable edit mode Grid.EditIndex = e.NewEditIndex; // Set status message statusLabel.Text = "Editing row # " + e.NewEditIndex.ToString(); // Reload the grid BindGrid(); } The RowCancelingEdit Event: protectedvoidGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { // Cancel edit mode Grid.EditIndex = -1; // Set status message statusLabel.Text = "Editing canceled"; // Reload the grid BindGrid(); } The RowUpdating Event: protectedvoidGrid_RowUpdating(object sender, GridViewUpdateEventArgs e) { // Retrieve updated data string id = Grid.DataKeys[e.RowIndex].Value.ToString(); string name = ((TextBox)Grid.Rows[e.RowIndex].Cells[1].Controls[0]).Text; string description = ((TextBox)Grid.Rows[e.RowIndex].Cells[2].Controls[0]).Text; // Execute the update command bool success = UpdateCategory(id, name, description); // Cancel edit mode 8 Grid.EditIndex = -1; // Display status message statusLabel.Text = success ?"Update successful" :"Update failed"; // Reload the grid BindGrid(); } The RowDeleting Event: protectedvoidGrid_RowDeleting(object sender, GridViewDeleteEventArgs e) { // Get the ID of the record to be deleted string id = Grid.DataKeys[e.RowIndex].Value.ToString(); // Execute the delete command bool success = DeleteCategory(id); // Cancel edit mode Grid.EditIndex = -1; // Display status message statusLabel.Text = success ?"Delete successful" :"Delete failed"; // Reload the grid BindGrid(); } 9