Figure 1 Design to Allow Insertion Into a Gridview
Total Page:16
File Type:pdf, Size:1020Kb
Lab 9 – G9idView 3
Introduction
The tutorial shows how to insert a new row into the database and update the GridView as shown in Figure 1 below. This is exactly the same as Lab 8 except for this new feature. We also show how to confirm a delete on the client and add a validator inside the GridView to restrict the Jersey number (PNumber) to be between 1 and 99.
Figure 1 – Design to allow Insertion into a GridView.
Lab Objectives:
1. Allow the user to insert a row into a GridView. 2. Confirm a deletion from the GridView. 3. Utilize a validator inside the GridView to constrain the user’s input.
There are 8 stages to complete Lab 9.
Stage Description 1 Create Lab 9 Home Page 2 Add Insert Feature 3 Confirming a Delete on the Client 4 Adding a Validator 5 Updating the Select Event Code 6 Wrapping Up and Posting to Lucius
Follow the directions below to complete the lab. The completed Lab should work like this: https://lucius.valdosta.edu/dgibson/labs/lab9_sp15_2/Default.aspx
1 Stage 1 – Create Lab 9 Home Page
We will begin by copying your Lab 8 work and then Stage 2 will implement some new pieces of functionality.
1. Do the following:
a. In Windows, copy your lab8 folder and give it the new name, lab9. b. Open the folder and delete the .sln and .sou files if they are present. c. Open VS and choose: File, Open, Web Site and navigate to the lab9 folder. d. Change the HTML title to: Lab 9… e. Change the Level 2 header to: Lab 9… f. Put a link from your course home page to the Lab 9 home page. g. (Optional) Save the solution as lab9.sln to the lab9 folder:
i. Select the Solution node in the Solution Explorer as shown on the right.
ii. Choose: File, Save lab9.sln As…
iii. Navigate to your lab9 folder and save.
2. Build and run your page (Ctrl+Shift+B, Ctrl+F5). Test thoroughly.
Stage 2 – Add Insert Feature
3. Just below the Lab 9 h2 header and above the GridView, add the markup below to the Source to create input fields for adding a new row to the database as shown below.
Last Name
2 4. Configure the DropDownList above to be bound to a DataSource which displays the Name as the Text and TeamID as the Value (from the Teams table). Hint: See Lab 8 if you need help with this.
5. Build and run your page (Ctrl+Shift+B, Ctrl+F5). Make sure the teams are displayed in the drop down.
6. When we created the DataSource in Lab 7 (and 8) we pressed “Advanced” and had it, “Generate INSERT, UPDATE, and DELETE statements” (See Lab 7, Stage 2, steps 11 & 12 if needed). The GridView itself uses the UPDATE and DELETE statements to carry out those actions. However, the INSERT statement is not use as the GridView does not have a mechanism to insert a new row in the database. But, we can use the DataSource’s INSERT statement programmatically to insert a row. Do the following:
a. Create an Add button event handler by double-clicking the Add button in Design mode. b. Add this code to the event handler.
dsSqlServerPlayers.InsertParameters["TeamID"].DefaultValue = ddTeams.SelectedValue; dsSqlServerPlayers.InsertParameters["LName"].DefaultValue = txtLName.Text; dsSqlServerPlayers.InsertParameters["FName"].DefaultValue = txtFName.Text; dsSqlServerPlayers.InsertParameters["PNumber"].DefaultValue = txtPNumber.Text; dsSqlServerPlayers.InsertParameters["BDate"].DefaultValue = txtBDate.Text;
dsSqlServerPlayers.Insert();
// Clear fields txtLName.Text = string.Empty; txtFName.Text = string.Empty; txtPNumber.Text = string.Empty; txtBDate.Text = string.Empty;
7. Build and run your page (Ctrl+Shift+B, Ctrl+F5). Test thoroughly. Insert a player and verify that it is there.
Stage 3 – Confirming a Delete on the Client
We will next require the user to be confirm a delete from the GridView. To do this we will remove the “automatic” Delete button and put in a new one that allows us to intercept the deletion and do a custom confirmation.
8. Display the flyout menu for the GridView and uncheck “Enable Delete”.
3 9. Display the “GridView Tasks” menu, choose “Edit Columns...” to display the Fields dialog, then:
a. Select TemplateField from the “Available fields” and choose “Add”.
b. Select TemplateField from the “Selected fields” and then click the up arrow to raise it to just below CommandField (this moves the TemplateField left in the GridView display).
c. Choose “OK”.
10. Display the “GridView Tasks” menu and choose “Edit Templates”. Make sure the ItemTemplate is displayed. Put a LinkButton in the ItemTemplate (i.e. drag a LinkButton from the ToolBox).
11. Select the LinkButton and set the properties shown below.
a. Set the CommandName property to “Delete”. This synchs the LinkButton’s Click event with GridView’s DeleteCommand, which contains the SQL for a Delete statement.
b. Set the OnClientClick property to “return ConfirmDelete()”. This specifies a JavaScript function (that runs on the client) that returns true or false. If true, the page posts-back and the deletion is carried out on the server. If false, the page does not post back (i.e. the deletion is aborted). In this case, the JavaScript function name is ConfirmDelete which we will add to the Source in the next step.
c. Set the Text property to “Delete” which is the text that appears on the LinkButton.
d. Display the GridView Tasks menu and “End Template Editting.”
12. Add the JavaScript function below in the Source (in the head section). You could have a more elaborate function that displays the values of the row that is about to be deleted; however, this is a good bit more involved.
13. Build/Run (Ctrl+Shift+B, Ctrl+F5). Test the confirmation of deletion.
4 Stage 4 – Adding a Validator
We will add a RangeValidator to the Jersey Number (PNumber) field in the GridView when in Edit mode so that a Jersey Number can only be between 1 and 99.
14. Display the “GridView Tasks” menu and choose “Edit Columns.”
15. Select “PNumber” and “Convert this field into a Template Field” (lower right). Then choose OK.
Do the following:
a. Display the “GridView Tasks” menu and choose “Edit Templates.”
b. Select “Column[6] – PNumber” from the Display drop down.
c. Select the Label in the ItemTemplate and supply it the ID: gvLblPNum. We will use this later.
5 6 d. (This step is for information only).
i. Select the label, then click the arrow icon, then select “Edit DataBindings.”
ii. The display will look like this. We will not change anything here. Notice how the Text property is bound to the PNumber field under “Custom binding”. Choose Cancel.
e. Select the TextBox in the EditItemTemplate (see Step 15 c above) and provide the ID, gvTxtPNum.
f. (This step is for information only). Select the TextBox in the EditItemTemplate and choose: “Edit DataBindings”. Inspect the Text property binding and then Cancel.
16. Drag a “RangeValidator” from the ToolBox into the EditItemTemplate, beside the Textbox. Set the following properties:
Property Value ControlToValidate gvTxtPNum ErrorMessage Jersey Number must be between 1 and 99. Font/Bold True ForeColor Red MaximumValue 99 MinimumValue 1 SetFocusOnError True Text * Type Integer Width 20
17. When complete, display the “GridView Tasks” menu select End Template Editing.
7 18. Drag a “ValidationSummary” from the ToolBox to just above the GridView (and below the Add feature). Set the following properties:
Property Value Font/Bold True ForeColor Red
19. Open Web.config. Add the appSettings node above (or below) the system.web node.
20. Build/Run (Ctrl+Shift+B, Ctrl+F5). Test the validation. It should work. If not, go back over the previous steps. Test the Select feature. It will fail. We will fix that in the next section.
21. (Information only) View the Source for the page. Find the GridView and then find the PNumber TemplateField inside the GridView. Study the structure. Note the two Bind statements as shown highlighted in yellow below.
8 Stage 5 – Updating the Select Event Code
Left off here!~!!!!!~!~@!~!~@#@!~!~
22. If you have not coded the GridView’s SelectedIndexChanged event, create that event handler now. (Select GridView, select Events icon in Properties Window, double-click the SelectedIndexChanged event.)
If you have already coded this event, you have noticed that it doesn’t work for several reasons:
a. When we added the Delete LinkButton, this messed up the numbering of the cells, e.g. “Edit Select” is Cell 0, “Delete” is Cell 1, “PlayerID” is Cell 2, etc.
b. “PNumber” is now a template field and we have to reference it differently.
23. The complete event handler should look like as shown below. Note: if you did not put in the HiddenField to store the TeamID, see Step 49 in Lab 8.
protected void gvPlayers_SelectedIndexChanged(object sender, EventArgs e) { // Bound Fields int playerID = Convert.ToInt32(gvPlayers.SelectedRow.Cells[2].Text); string lName = gvPlayers.SelectedRow.Cells[4].Text; string fName = gvPlayers.SelectedRow.Cells[5].Text; //int jerseyNum = Convert.ToInt32(gvPlayers.SelectedRow.Cells[5].Text); DateTime bDate = Convert.ToDateTime(gvPlayers.SelectedRow.Cells[7].Text);
// Template Fields Label lblTeamName = (Label)gvPlayers.SelectedRow.FindControl("gvLblTeamName"); string teamName = lblTeamName.Text;
Label lblJerseyNum = (Label)gvPlayers.SelectedRow.FindControl("gvLblPNum"); int jerseyNum = Convert.ToInt32(lblJerseyNum.Text);
// Hidden Field HiddenField teamIDHidden = (HiddenField)gvPlayers.SelectedRow.FindControl("TeamIDHidden");
string teamID = teamIDHidden.Value;
string output = String.Format("PlayerID={0}, LName={1}, FName={2}, " + "JerseyNum={3}, BDate={4}, " + "Team={5}, TeamID={6}", playerID, lName, fName, jerseyNum, bDate.ToShortDateString(), teamName, teamID); txtMsg.Text = output; }
24. Build/Run (Ctrl+Shift+B, Ctrl+F5). Test thoroughly.
9 Stage 6 – Wrapping Up and Posting to Lucius
25. Make sure that your Identity node: