2015-12-04 2 views
0

Я пытаюсь изменить команду в моей базе данных, я получаю всю соответствующую информацию, но когда я нажимаю «ОК», вся переменная сбрасывается, что является ожидаемым поведением, но мне нужно сохранить идентификатор, чтобы гарантировать, что я совершаю редактирование. Мне было интересно, если кто-нибудь знает, как это сделать, у меня есть googled, используя все виды поисковых запросов, и все это связано с MVC, который я не использую.Сохранение идентификатора при редактировании записи в базе данных

Соответствующий код ниже.

Public Class 
Inherits System.Web.UI.Page 

Private f_conAdministrator As OleDb.OleDbConnection ' Import System.Data.OleDB 

' -------------------------------------------------------------------------------- 
' Form Variables 
' -------------------------------------------------------------------------------- 
Private f_blnResult As Boolean  ' Don't use DialogResult since it triggers a cascade close 
Private f_intTeamID As Integer 

' -------------------------------------------------------------------------------- 
' Name: Page_Load 
' Abstract: Handles the Page load event 
' -------------------------------------------------------------------------------- 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 

    Try 

     Dim blnResult As Boolean = False 

     ' First time the page is loaded? 
     If Page.IsPostBack = False Then 

      ' Load the exiting Team data 
      blnResult = LoadTeam() 

      ' Did it work? 
      If blnResult = False Then 

       ' No, warn the user ... 
       SendMessageToClient("Unable to load team information from the database\n" & "The form will now close.") 

       ' Close the form 

       ' False = don't generate exception. This is a planned redirect. 
       Response.Redirect("./WManageTeams.aspx", False) 

      End If 

     End If 

    Catch excError As Exception 

     ' Log and display error message 
     WriteLog(excError) 

    End Try 

End Sub 



' -------------------------------------------------------------------------------- 
' Name: LoadTeam 
' Abstract: Get the team information from the database and populate the 
'   form field with it 
' -------------------------------------------------------------------------------- 
Private Function LoadTeam() As Boolean 

    Dim blnResult As Boolean = False 

    Try 

     Dim udtTeam As udtTeamType = New udtTeamType 

     ' Which team do we edit? 
     f_intTeamID = Val(Request.QueryString("intTeamID")) 
     udtTeam.intTeamID = f_intTeamID 

     ' Open DB connection 
     If OpenDatabaseConnectionMSAccess() = True Then 

      ' Do it 
      blnResult = GetTeamInformationFromDatabase(udtTeam) 

      ' Did it work? 
      If blnResult = True Then 

       ' Yes 
       txtTeam.Text = udtTeam.strTeam 
       txtMascot.Text = udtTeam.strMascot 

       ' Set focus to Team name and select existing text 
       txtTeam.Focus() 

      End If 

      ' Close the conection 
      CloseDatabaseConnection() 

     End If 

    Catch excError As Exception 

     ' Log and display error message 
     WriteLog(excError) 

    End Try 

    Return blnResult 

End Function 



' -------------------------------------------------------------------------------- 
' Name: btnOK_Click 
' Abstract: If the data is good then save the changes 
' -------------------------------------------------------------------------------- 
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOk.Click 

    Try 

     ' Is the data OK? 
     If IsValidData() = True Then 

      ' Open a connection 
      If OpenDatabaseConnectionMSAccess() = True Then 

       ' Yes, save 
       If SaveData() = True Then 

        ' If the save was successful then ... 

        ' Success 
        f_blnResult = True 

       End If 

       ' Close the Connection 
       CloseDatabaseConnection() 

      End If 

      ' Did it work? 
      If f_blnResult = True Then 

       ' Yes, redirect. False = don't generate exception. This is a planned redirect. 
       Response.Redirect("./WManageTeams.aspx?intTeamID=" & f_intTeamID, False) 

      End If 

     End If 

    Catch excError As Exception 

     ' Log and display error message 
     WriteLog(excError) 

    End Try 

End Sub 


' -------------------------------------------------------------------------------- 
' Name: GetTeamInformationFromDatabase 
' Abstract: Get data for the specified team from the database 
' -------------------------------------------------------------------------------- 
Public Function GetTeamInformationFromDatabase(ByRef udtTeam As udtTeamType) As Boolean 

    Dim blnResult As Boolean = False 

    Try 

     Dim strSelect As String = "" 
     Dim cmdSelect As New OleDb.OleDbCommand 
     Dim drTTeams As OleDb.OleDbDataReader 

     ' Build the select string 
     strSelect = "SELECT *" & _ 
        " FROM TTeams" & _ 
        " WHERE intTeamID = " & udtTeam.intTeamID 

     ' Retrieve the record 
     cmdSelect = New OleDb.OleDbCommand(strSelect, f_conAdministrator) 
     drTTeams = cmdSelect.ExecuteReader 

     ' Read (there should be 1 and only 1 row) 
     drTTeams.Read() 
     With drTTeams 
      udtTeam.strTeam = .Item("strTeam") 
      udtTeam.strMascot = .Item("strMascot") 
     End With 

     ' Clean up 
     drTTeams.Close() 

     ' Success 
     blnResult = True 

    Catch excError As Exception 

     ' Log and display error message 
     WriteLog(excError) 

    End Try 

    Return blnResult 

End Function 

ответ

0

Вы можете сохранить его в переменной сеанса, как показано ниже: -

f_intTeamID = Val(Request.QueryString("intTeamID")) 
Session("f_intTeamID") = f_intTeamID 

В следующий раз, когда страница отправлять обратно затем извлечь его из сессии.

+0

То, что мне было нужно, спасибо. Надеюсь, этот пост поможет кому-то еще в будущем. Спасли меня, наверное, 10 часов тупиков, пока я его не нашел. Спасибо. –

0

Как и в первом запросе при загрузке данных, вы также можете прочитать его из параметров запроса в запросе PostBack:

f_intTeamID = Val(Request.QueryString("intTeamID")) 

Экземпляр, который служит запрос создается только для конкретный запрос и выбросить потом. Когда новый запрос поступает на сервер после того, как пользователь нажал кнопку OK, создается новый экземпляр. Вот почему значения переменных исчезли.

Как вам может понадобиться идентификатор в каждом запросе, вы можете добавить инструкции к методу Page_Load, чтобы переменная была установлена, когда вам это нужно.

+0

ваше высказывание просто перемещает f_intTeamID = Val (Request.QueryString ("intTeamID")) в мою процедуру page_load? –

+0

@AdamSchneider: да, это должно сделать это. Это должна быть одна из первых строк. – Markus

+0

Должен ли я поставить его вне моего блока Try? –

Смежные вопросы