• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 420
  • Last Modified:

IsPostBack problem

I have a datagrid on a page that works fine except for when I call the cancel and update events - these don't fire at all.

I've tried using if not ispostback ...

      If Not Page.IsPostBack Then
            bindData() 'Only bind the data on the first page load
       End If

... as I was advised that this was causing the problem but when I use this no events fire AT ALL and the Datagrid doesn't load - basically I get a blank screen.

Can anyone tell me what's going on and how I can correct the problem please.


HTML CODE

<!-- DATAGRID -->
<form id="Form1" method="post" runat="server">
<asp:Label id="Label1" runat="server" Font-Bold="True" Font-Names="Arial" Font-Size="Medium">Aviagen Registered Users</asp:Label><br>
<br>
<asp:datagrid id="DataGrid1" runat="server" Width="700px" BorderColor="#DEBA84" BorderStyle="None"
      BorderWidth="1px" BackColor="#DEBA84" CellPadding="3" CellSpacing="2" AutoGenerateColumns="False"
      OnItemCommand="eventHandler" AllowSorting="True" OnSortCommand="SortEventHandler" OnEditCommand="editEventHandler"
      OnCancelCommand="cancelEventHandler" OnUpdateCommand="updateEventHandler">
      <FooterStyle ForeColor="#8C4510" BackColor="#F7DFB5"></FooterStyle>
      <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#738A9C"></SelectedItemStyle>
      <ItemStyle ForeColor="#8C4510" BackColor="#FFF7E7"></ItemStyle>
      <HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#A55129"></HeaderStyle>
      <Columns>
            <asp:BoundColumn DataField="firstName" SortExpression="firstName" HeaderText="First Name"></asp:BoundColumn>
            <asp:BoundColumn DataField="lastname" SortExpression="lastName" HeaderText="Last Name"></asp:BoundColumn>
            <asp:BoundColumn DataField="company" SortExpression="company" HeaderText="Company"></asp:BoundColumn>
            <asp:BoundColumn DataField="dateRegistered" SortExpression="dateRegistered" HeaderText="Joined" DataFormatString="{0:MM-dd-yyyy}"></asp:BoundColumn>
            <asp:BoundColumn DataField="email" HeaderText="Email"></asp:BoundColumn>
            <asp:BoundColumn Visible="False" DataField="aviagenId" HeaderText="Aviagen ID"></asp:BoundColumn>
            <asp:ButtonColumn Text="Delete" ButtonType="PushButton" HeaderText="Delete" CommandName="deleteUser"></asp:ButtonColumn>
            <asp:EditCommandColumn ButtonType="PushButton" UpdateText="Update" HeaderText="Amend" CancelText="Cancel"
                  EditText="Edit"></asp:EditCommandColumn>
      </Columns>
</asp:datagrid>

</form>
<!-- END OF DATAGRID -->




VB CODE


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not Page.IsPostBack Then
            bindData() 'Only bind the data on the first page load
        End If
    End Sub

    Sub eventHandler(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        'Determine which is called command
        If e.CommandName = "deleteUser" Then
            Response.Write("delete button pressed - User: " & e.Item.Cells(0).Text & " " & e.Item.Cells(1).Text)
            'Delete user from database
        End If
        bindData()
    End Sub

    Sub SortEventHandler(ByVal sender As Object, ByVal e As DataGridSortCommandEventArgs)
        'Call function to sort data
        bindData(e.SortExpression)
        Response.Write("records sorted by " & e.SortExpression)
    End Sub

    Sub editEventHandler(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        Response.Write(e.Item.Cells(0).Text & " " & e.Item.Cells(1).Text & " selected for editing")
        'Let the DataGrid know what row to edit
        DataGrid1.EditItemIndex = e.Item.ItemIndex
        bindData()
    End Sub

    Sub cancelEventHandler(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        Response.Write("Edit Cancelled")
        'Cancel edit mode
        DataGrid1.EditItemIndex = -1
        bindData()
    End Sub

    Sub updateEventHandler(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        Response.Write(e.Item.Cells(0).Text & " " & e.Item.Cells(1).Text & " details updated")
        'Read in the values of the updated row - i.e. and then do the updating
        'Re-Bind the data        
        bindData()
    End Sub

    Sub bindData()
        '1. Create a connection
        Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("sqlConnectionString"))

        '2. Create the command object, passing in the SP name
        Const strSQL As String = "select top 10 * from registration_new"
        Dim myCommand As New SqlCommand(strSQL, myConnection)

        '3. Set the datagrid's datasource to the datareader and databind
        myConnection.Open()

        DataGrid1.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
        DataGrid1.DataBind()
    End Sub

    Sub bindData(ByVal sortExpr As String) 'A bit of polymorphism here - same sub name but now with parameter
        '1. Create a connection
        Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("sqlConnectionString"))

        '2. Create the command object, passing in the SQL string
        Dim strSQL As String = "select top 10 * from registration_new WHERE " & sortExpr & " IS NOT NULL ORDER BY " & sortExpr
        Dim myCommand As New SqlCommand(strSQL, myConnection)

        'Set the datagrid's datasource to the datareader and databind
        myConnection.Open()
        DataGrid1.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
        DataGrid1.DataBind()
    End Sub



0
gbzhhu
Asked:
gbzhhu
  • 3
  • 3
1 Solution
 
RamuncikasCommented:
try

        '3. Set the datagrid's datasource to the datareader and databind
        myConnection.Open()

        DataGrid1.DataSource = myCommand.ExecuteReader()
        DataGrid1.DataBind()
        myConnection.Close()
0
 
bsdotnetCommented:
I tested your code in vwd2005 and it worked (except that i need to add below changes),

change the updateEventHandler to,
   Sub updateEventHandler(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("sqlConnectionString"))
        myConnection.Open()
        Dim Sql = "Update table1 Set firstname=@firstname, lastname=@lastname, company=@company, dateregistered=@dateregistered, email=@email Where aviagenid=@aviagenid"
        Dim cmd As New SqlCommand(Sql, myConnection)
        cmd.Parameters.AddWithValue("@aviagenid", DataGrid1.DataKeys(e.Item.ItemIndex))
        cmd.Parameters.AddWithValue("@firstname", CType(e.Item.Cells(0).Controls(0), TextBox).Text)
        cmd.Parameters.AddWithValue("@lastname", CType(e.Item.Cells(1).Controls(0), TextBox).Text)
        cmd.Parameters.AddWithValue("@company", CType(e.Item.Cells(2).Controls(0), TextBox).Text)
        cmd.Parameters.AddWithValue("@dateregistered", CType(e.Item.Cells(3).Controls(0), TextBox).Text)
        cmd.Parameters.AddWithValue("@email", CType(e.Item.Cells(4).Controls(0), TextBox).Text)
        cmd.ExecuteNonQuery()
        myConnection.Close()
        DataGrid1.EditItemIndex = -1
        bindData()
    End Sub

Secondly, pls add DataKeyField="aviagenId" to your asp:DataGrid tag, (I assume this is your primary key)
<asp:datagrid id="DataGrid1" DataKeyField="aviagenId" runat="server" ...
0
 
bsdotnetCommented:
If you are using 1.1, replace cmd.Parameters.AddWithValue with cmd.Parameters.Add in Sub updateEventHandler
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
gbzhhuAuthor Commented:
Hi,  I've tried Ramuncikas suggestion but it made no difference.  I'm gutted that it works for bsdotnet in 2005 and not me in 2003.

(Thanks anyway for your help by the way guys)

Anyone else come across a similar problem?

0
 
bsdotnetCommented:
I tested in 2003 and it worked!!!
0
 
gbzhhuAuthor Commented:
We tried on VS 2003 on 2 different machines with the same result (not working!)  Here is the whole code, see if you can spot any differences

ASPX code

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="DataGrid.aspx.vb" Inherits="servercontrols.dbt.co.uk.DataGrid"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
      <HEAD>
            <title>DATAGRID</title>
            <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
            <meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
            <meta content="JavaScript" name="vs_defaultClientScript">
            <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
      </HEAD>
      <body>
            <!-- DATAGRID -->
            <form id="Form1" method="post" runat="server">
                  <asp:Label id="Label1" runat="server" Font-Bold="True" Font-Names="Arial" Font-Size="Medium">Aviagen Registered Users</asp:Label><br>
                  <br>
                  <asp:datagrid id="DataGrid1" runat="server" Width="700px" BorderColor="#DEBA84" BorderStyle="None"
                        BorderWidth="1px" BackColor="#DEBA84" CellPadding="3" CellSpacing="2" AutoGenerateColumns="False"
                        OnItemCommand="eventHandler" AllowSorting="True" OnSortCommand="SortEventHandler" OnEditCommand="editEventHandler"
                        OnCancelCommand="cancelEventHandler" OnUpdateCommand="updateEventHandler">
                        <FooterStyle ForeColor="#8C4510" BackColor="#F7DFB5"></FooterStyle>
                        <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#738A9C"></SelectedItemStyle>
                        <ItemStyle ForeColor="#8C4510" BackColor="#FFF7E7"></ItemStyle>
                        <HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#A55129"></HeaderStyle>
                        <Columns>
                              <asp:BoundColumn DataField="firstName" SortExpression="firstName" HeaderText="First Name"></asp:BoundColumn>
                              <asp:BoundColumn DataField="lastname" SortExpression="lastName" HeaderText="Last Name"></asp:BoundColumn>
                              <asp:BoundColumn DataField="company" SortExpression="company" HeaderText="Company"></asp:BoundColumn>
                              <asp:BoundColumn DataField="dateRegistered" SortExpression="dateRegistered" HeaderText="Joined" DataFormatString="{0:MM-dd-yyyy}"></asp:BoundColumn>
                              <asp:BoundColumn DataField="email" HeaderText="Email"></asp:BoundColumn>
                              <asp:BoundColumn Visible="False" DataField="aviagenId" HeaderText="Aviagen ID"></asp:BoundColumn>
                              <asp:ButtonColumn Text="Delete" ButtonType="PushButton" HeaderText="Delete" CommandName="deleteUser"></asp:ButtonColumn>
                              <asp:EditCommandColumn ButtonType="PushButton" UpdateText="Update" HeaderText="Amend" CancelText="Cancel"
                                    EditText="Edit"></asp:EditCommandColumn>
                        </Columns>
                  </asp:datagrid>
            </form>
            <!-- END OF DATAGRID -->
      </body>
</HTML>


Code behind

Imports System.Configuration
Imports System.Web
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Imports System.Xml




Public Class DataGrid
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid
    Protected WithEvents Label1 As System.Web.UI.WebControls.Label

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()

    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'If Not Page.IsPostBack Then
        bindData() 'Only bind the data on the first page load
        'End If
    End Sub

    Sub eventHandler(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        'Determine which is called command
        If e.CommandName = "deleteUser" Then
            Response.Write("delete button pressed - User: " & e.Item.Cells(0).Text & " " & e.Item.Cells(1).Text)
            'Delete user from database
        End If
        bindData()
    End Sub

    Sub SortEventHandler(ByVal sender As Object, ByVal e As DataGridSortCommandEventArgs)
        'Call function to sort data
        bindData(e.SortExpression)
        Response.Write("records sorted by " & e.SortExpression)
    End Sub

    Sub editEventHandler(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        Response.Write(e.Item.Cells(0).Text & " " & e.Item.Cells(1).Text & " selected for editing")
        'Let the DataGrid know what row to edit
        DataGrid1.EditItemIndex = e.Item.ItemIndex
        Response.Write(e.Item.ItemIndex)
        bindData()
    End Sub

    Sub cancelEventHandler(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        Response.Write("Edit Cancelled")
        'Cancel edit mode
        DataGrid1.EditItemIndex = -1
        bindData()
    End Sub

    Sub updateEventHandler(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        Response.Write(e.Item.Cells(0).Text & " " & e.Item.Cells(1).Text & " details updated")
        'Read in the values of the updated row - i.e. and then do the updating
        'Re-Bind the data        
        bindData()
    End Sub

    Sub bindData()

        '1. Create a connection
        Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("sqlConnectionString"))

        ''2. Create the command object, passing in the SP name
        Const strSQL As String = "select top 10 * from registration_new"
        Dim myCommand As New SqlCommand(strSQL, myConnection)

        ''3. Set the datagrid's datasource to the datareader and databind
        myConnection.Open()

        DataGrid1.DataSource = myCommand.ExecuteReader()
        DataGrid1.DataBind()
    End Sub

    Sub bindData(ByVal sortExpr As String) 'A bit of polymorphism here - same sub name but now with parameter
        '1. Create a connection
        Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("sqlConnectionString"))

        '2. Create the command object, passing in the SQL string
        Dim strSQL As String = "select top 10 * from registration_new WHERE " & sortExpr & " IS NOT NULL ORDER BY " & sortExpr
        Dim myCommand As New SqlCommand(strSQL, myConnection)

        'Set the datagrid's datasource to the datareader and databind
        myConnection.Open()
        DataGrid1.DataSource = myCommand.ExecuteReader()
        DataGrid1.DataBind()
    End Sub


End Class

 
0
 
gbzhhuAuthor Commented:
WEIRDLY, THIS HAS JUST STARTED WORKING PROPERLY!!!!!!!!!

0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now