Search code examples
asp.netvb.netevents

Is there a way to run a method when the site is loaded, but not when it posts back (asp.net + vb.net)


Method using Handles MyBase.LoadIm trying to populate a drop down list with all times of the day in intervals of 30 minutes, instead of hard coding it, I made a loop which does create and add to the drop-down lists. The part that I'm stuck on is how to make it so that it only runs once at the first load of the page.

The only thing I've found on other posts are to make it so that it runs off an event. I've seen people say to add Handles MyBase.Load, but that also adds duplicates to the existing drop-down lists when another part of the page posts back.

Instead, I want it to just create and add the list items once when the page first is loaded, any help would be appreciated Thanks


Solution

  • Well, it of course makes no sense to try and load such data when the whole web site first starts up.

    As for a simple page post back?

    The last 200+ web pages I have created ALL HAVE a standard If not IsPostBack code stub in the page load event. In fact, you really can't even build a working web page if you don't adopt use of such a code stub.

    Remember, unlike desktop, on any post back, on any button click, the page load event fires each and every time first, and THEN your code behind stub for the button fires.

    Thankfully, we have the IsPostBack flag to test and check if this is in fact the first page load.

    So, say I want some drop down select start and end time for today, and hence we could have this markup:

            <div style="float: left">
                <h4>Select Start Time</h4>
                <asp:DropDownList ID="cboStart" runat="server"
                    DataValueField="Date"
                    DataTextField="TimeDisplay">
                </asp:DropDownList>
            </div>
    
            <div style="float: left;margin-left:35px">
                <h4>Select End Time</h4>
                <asp:DropDownList ID="cboEnd" runat="server"
                    DataValueField="Date"
                    DataTextField="TimeDisplay">
                </asp:DropDownList>
            </div>
    
            <div style="clear:both"></div>
            <br />
            <asp:Button ID="cmdShow" runat="server" Text="Show Selected time"
                CssClass="btn"
                OnClick="cmdShow_Click"/>
            <br />
            <br />
    
            <asp:Label ID="lblShowSelected" runat="server" Text="">
            </asp:Label>
    

    And for ease of coding, the display will be only the time, but selecting of the values will include the date + time, and this of course makes code less complex, since we always dealing with a valid datetime, and thus the selection can be for example used against a database.

    And the code behind is this:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
        If Not IsPostBack Then
            LoadCbo
        End If
    End Sub
    
    Sub LoadCbo()
    
        Dim dtTimes As New DataTable
        dtTimes.Columns.Add("Date", GetType(DateTime))
        dtTimes.Columns.Add("TimeDisplay", GetType(String))
    
        Dim dtStartDay = Date.Today
        Dim dtStartTime = TimeSerial(9, 0, 0) ' start at 9 am
    
        Do
            Dim NewRow = dtTimes.NewRow()
            NewRow("Date") = dtStartDay.Add(dtStartTime.TimeOfDay)
            NewRow("TimeDisplay") = dtStartTime.ToString("hh:mm tt")
            dtTimes.Rows.Add(NewRow)
    
            dtStartTime = dtStartTime.AddMinutes(30)
    
        Loop While Hour(dtStartTime) <= 17 ' go untill 5 pm
    
        cboStart.DataSource = dtTimes
        cboStart.DataBind()
        cboStart.Items.Insert(0, "Select start Time")
    
        cboEnd.DataSource = dtTimes
        cboEnd.DataBind()
        cboEnd.Items.Insert(0, "Select End Time")
    
    
    End Sub
    
    Protected Sub cmdShow_Click(sender As Object, e As EventArgs)
    
        Dim dtStart As DateTime = cboStart.SelectedItem.Value
        Dim dtEnd As DateTime = cboEnd.SelectedItem.Value
    
    
        Dim sMsg As String =
            $"Selected Time for {dtStart.ToString("dddd MMMM dd, yyyy")} Is <br/>
            {dtStart.ToString("hh:mm tt")} to {dtEnd.ToString("hh:mm tt")}"
    
        lblShowSelected.Text = sMsg
    
    End Sub
    

    In above, we load up the combo boxes in 30-minute increments, but you are free to change that to whatever you wish.

    Note the all important IsPostBack test. This means that setup code to load controls, and general page setup code only runs once on the first real page load. While for each button click etc. (post backs), the page load event does run first and then your code behind button click stub?

    It will not matter, since our "real" first page load code is inside of our IsPostBack test, and thus will only ever run one time on the first page load.

    The result of above is thus this:

    enter image description here

    Hence, we are free to now have button click events etc., and as such, they will not affect the code that loads up the controls such as the DropDownList (combo box) in this example.