Friday, March 16, 2012

Member parameters always set to null...?

Hello!

I've an ASP web page in which a button click handler requires access to the page's member parameters. Every time the button routine runs however, the member parameters seem to be null (values = NOTHING).

The code is appended below. Sorry for the length of the code, but I wanted to make sure I wasn't missing anything, and that my problem was clear.

The page initializes fine, and the date is pulled correctly and displayed in the grid upon load... but whenever the button routine commences, dsEmployee is a null value (I checked with the debugger).

I've tried prefacing the variable names with ME, but this changed nothing.

Since I'm a newbie, I've a sneaking suspicion that the solution will be so obvious as to verge on the ridiculous... Any ideas?

Imports System.Data.SqlClient
Imports System.Data

Partial Class AddEmployee
Inherits System.Web.UI.Page

Dim daEmployee As SqlDataAdapter
Dim dsEmployee As DataSet

Const stConnection As String = "Data Source=.\sqlexpress;Initial Catalog=dbBatteries;Integrated Security=True"

Const stSelect As String = "SELECT LastName, FirstName, Number, EmployeeID " + _
"FROM tblEmployee ORDER BY LastName"

Const stTableName As String = "Employee"

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not Me.IsPostBack Then

' data connection
daEmployee = New SqlDataAdapter(stSelect, stConnection)

' data island
dsEmployee = New DataSet(stTableName)

' fill data island
daEmployee.Fill(dsEmployee, stTableName)

' bind data to control
grdEmployee.DataSource = dsEmployee.Tables(stTableName)
grdEmployee.DataBind()

End If

End Sub

Protected Sub butInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butInsert.Click

'daEmployee.InsertCommand.CommandText = stInsert
Dim drEmployee As DataRow

' create a datarow object (there exists no constructor)
drEmployee = dsEmployee.Tables(stTableName).NewRow()

' fill in its values
drEmployee.Item("LastName") = txtLastName.Text
drEmployee.Item("FirstName") = txtFirstName.Text
drEmployee.Item("Number") = CInt(txtNumber.Text)

' add it to the data island
dsEmployee.Tables(stTableName).Rows.Add(drEmployee)

End Sub

End Classin ASP.NET, just like in classic ASP, objects are erased with every page refresh, thus since in yor load event you are not populating the objects if the page is a postback, they are empty.

Either use these variables in your button click, or else remove that if statement.
To preserve the dataset values, put it in viewstate.
Thanks guys! I've got it working now.

0 comments:

Post a Comment