Inserting Data

Inserting data works much the same way as updating data, but you use an insert command. There are many ways of handling the insert operation. The Web Form ch14-9.aspx handles it by checking the value of the lblstudentiD Label control. In the preceding section, the Web Form ch14-8.aspx set the value of that label to the string value of the selected student's StudentID. In addition, the Update Name button is visible only when the user is adding either a new name or an existing name. Therefore, when the Update Name button Click event fires, if the lblstudentiD Label control has no value, the user is adding a new name. There's one other consideration. The Students table has a column called Grade, which you didn't deal with in the preceding sections. To insert a new row, you must have a Grade value, so the Web Form adds a DropDownList control that lets the user select the new student's grade. Of course, that adds one more validation check because you can't provide a default value—there's no such thing as grade 0. Therefore, you must ensure that the user has selected a grade. Figure 14.14 shows how the Web Form looks when you first run it. Note the AddStudent button.

Figure 14.14: The Web Form chl4-9.aspx lets a user edit, delete, and insert students

Figure 14.14: The Web Form chl4-9.aspx lets a user edit, delete, and insert students

Warning Be sure to define the cascading delete relationship in the database before running the chl4-9.aspx example; otherwise, you'll get an error if you try to use cascading deletes to delete a student. See the section "Deleting Data Using Cascading Delete Relationships" earlier in this chapter for more information.

When a user clicks the AddStudent button, the Web Form displays a group of controls for entering a name and selecting the grade for the new student (see Figure 14.15).

Except for the routine that inserts the new student row, I won't display the code for the Web Form here because of its similarity to the chl4-8.aspx example.

private void insertName(String last, String first, String Grade) {

SqlConnection conn = new SqlConnection

(ConfigurationSettings.AppSettings.Get("ClassRecordsSql"));

SqlCommand cm = new SqlCommand("INSERT INTO Students " +

"(LastName, FirstName,Grade) VALUES ('" + last + "','" + first + "', " + Grade + ")", conn);

cm.ExecuteNonQuery();

showAddNameGroup(false);

catch (Exception ex) {

lblStudentNameError.Text = ex.Message;

finally {

Figure 14.15: The Web Form ch14-9.aspx lets a user edit, delete, and insert students

Was this article helpful?

0 0

Post a comment