beginner question about page_load

M

Michelle

I wrote a simple app to retrieve and update the Customer table in
Northwind database.

But I noticed the table displayed wouldn't be updated until I click the
update button for the second time.

This confuses me, anyone can understand and kindly explain?

Thanks much!

Following is the code

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
conn = New SqlConnection("Data Source=(local);Initial
Catalog=Northwind;Integrated Security=SSPI")
ds = New DataSet
da = New SqlDataAdapter

If Not IsPostBack Then
DisplayCustomers()
End If
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

Dim selectCmd As SqlCommand = conn.CreateCommand
selectCmd.CommandType = CommandType.Text
selectCmd.CommandText = "Select CustomerID, ContactName from
Customers"

Dim updateCmd As SqlCommand = conn.CreateCommand
updateCmd.CommandType = CommandType.Text
updateCmd.CommandText = "Update Customers set
ContactName=@ContactName where CustomerID=@CustomerID"
updateCmd.Parameters.Add("@ContactName", SqlDbType.NVarChar,
30, "ContactName")
updateCmd.Parameters.Add("@CustomerID", SqlDbType.NChar, 5,
"CustomerID")
updateCmd.Parameters("@CustomerID").SourceVersion =
DataRowVersion.Original

' Dim da As SqlDataAdapter = New SqlDataAdapter
da.SelectCommand = selectCmd
da.UpdateCommand = updateCmd

da.Fill(ds, "Customers")
Dim adrEdit() As DataRow =
ds.Tables("Customers").Select("CustomerID='" & TextBox1.Text & "'")

If UBound(adrEdit) > -1 Then
adrEdit(0)("ContactName") = TextBox2.Text
da.Update(ds, "Customers")
End If

DisplayCustomers()

End Sub

Private Sub DisplayCustomers()
Dim viewCmd As SqlCommand = conn.CreateCommand
viewCmd.CommandType = CommandType.Text
viewCmd.CommandText = "Select * from Customers order by
CustomerID ASC"

da.SelectCommand = viewCmd
da.Fill(ds, "AllCustomers")

DataGrid1.DataSource = ds.Tables("AllCustomers")
DataGrid1.DataBind()

End Sub
End Class
 
W

W.G. Ryan MVP

You're calling DisplayCustomers twice effectively here whenever there's a
postback. If you only want the stuff to refresh when a button is clicked,
you can take out the If Not Page.IsPostBack b/c Button1_Click is calling the
same thing.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top