Imports System.Data
Imports System.Data.SqlClient

Partial Class Insert
    Inherits System.Web.UI.Page
    Public FacultyName As String        'used for validation later by Faculty page.

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Application("sqlConnection").State <> ConnectionState.Open Then
            Application("sqlConnection").Open()
        End If
    End Sub

    Protected Sub cmdBack_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdBack.Click
        Response.Redirect("Faculty.aspx")
    End Sub

    Protected Sub cmdInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdInsert.Click
        Dim cmdString As String = "INSERT INTO Faculty (faculty_id, name, office, phone, college, title, email) " & _
                                  "VALUES (@faculty_id, @name, @office, @phone, @college, @title, @email)"
        Dim sqlCommand As New SqlCommand
        Dim FacultyImage As String
        Dim intInsert As Integer

        FacultyImage = txtPhoto.Text                'display the new inserted faculty photo
        If FacultyImage = String.Empty Then
            FacultyImage = "Default.jpg"
        End If
        Application("FacultyImage") = FacultyImage  'reserve faculty image for validation
        PhotoBox.ImageUrl = FacultyImage
        FacultyName = txtName.Text                  'reserve faculty name for validation
        Application("FacultyName") = FacultyName
        sqlCommand.Connection = Application("sqlConnection")
        sqlCommand.CommandType = CommandType.Text
        sqlCommand.CommandText = cmdString
        InsertParameters(sqlCommand)
        intInsert = sqlCommand.ExecuteNonQuery()
        sqlCommand.Dispose()
        sqlCommand = Nothing
        If intInsert = 0 Then
            Response.Write("<script>alert('The data insertion is failed')</script>")
            Exit Sub
        End If
        cmdInsert.Enabled = False           'disable the Insert button
    End Sub

    Private Sub InsertParameters(ByRef cmd As SqlCommand)
        cmd.Parameters.Add("@faculty_id", SqlDbType.Char).Value = txtID.Text
        cmd.Parameters.Add("@name", SqlDbType.Char).Value = txtName.Text
        cmd.Parameters.Add("@office", SqlDbType.Char).Value = txtOffice.Text
        cmd.Parameters.Add("@phone", SqlDbType.Char).Value = txtPhone.Text
        cmd.Parameters.Add("@college", SqlDbType.Char).Value = txtCollege.Text
        cmd.Parameters.Add("@title", SqlDbType.Char).Value = txtTitle.Text
        cmd.Parameters.Add("@email", SqlDbType.Char).Value = txtEmail.Text
    End Sub
End Class
