Avatar of JT_SIRO
JT_SIRO asked on

ASP.NET Page load order - How to trigger button click first

I should know this by now but don't...  How do I handle the case when I want a button click to fire before my page load event?  Or how can I prevent some of my page_load event code from running when button1 is clicked.  
C#.NET ProgrammingASP.NET

Avatar of undefined
Last Comment
maymounlb

8/22/2022 - Mon
Vikram Singh Saini

There are two questions you asked:

For first one:
There are three types of server control events-
1. Postback - For Button, ImagButton and LinkButtons.
2. Cached- Saved in page's view state (dropdownlist, checkboxlist, radiobuttons and more)
3. Validation - When you apply some validation on some control (generally on textbox)

And when a page is posted back these events fired in reverse order starting from Validation, Cached and then Postback. And after the firing of event is completed Asp.net engine recompiles page into html and send it as response to browser(user). so button click event is fired before Page_Load event.

For second one:
Make some static boolean variable for checking if the button is clicked or not. If button is clicked then assign true value to it. And then in page load event handler write code as

 static bool check;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(check)
        {
              //Write your code here which you dont want to run when button is clicked
        }
    }
SOLUTION
Aksh

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
JT_SIRO

vs - I don't see how the button_click event is fired before page_load.  I've never seen that.  I put break points on both, and page_load always fires first.  

This page is fairly complex, and a bit odd requirement wise.  I normally wouldn't build my primary grid on every postback, but I needed to do it this way because I've turned Serialization (or viewstate) off, for my primary grid, because it contains a lot of data and I want to post back when the user pages.  

Anyhow, Aksh here's my codebehind, if it helps.  Thanks
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Text;
using Obout.Grid;
using OboutInc.FileUpload;
using OboutInc;
using System.Threading;

public partial class Composer_Pages_SubmitForJob : System.Web.UI.Page
{
    protected void Page_Init()
    {
        //AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
        //trigger.ControlID = imgAdd.Click();
        //UpdatePanel1.Triggers.Add(trigger);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // hide instructions and show grid
        lblInstructions.Visible = false;
        gvPlaylist.Visible = true;

        // Populate the main grid with the users catalog of tracks - done here in order for the grid to page with serialization turned off //
        fillMainGrid();


        if (!IsPostBack)
        {
            if (Session["sSelectedJob"] != null)
            {
                ddJob.SelectedValue = Session["sSelectedJob"].ToString();   // Set the Job in the drop box with last visit
                lblInstructions.Visible = false;    // Hide instructions
                UpdatePlaylistGrid();
            }
            else
            {
                // Hide the Playlist grid
                gvPlaylist.Visible = false;
            }

            if (Request.QueryString["type"] == "qs")
            {
                // Hide Catalog / Show Quick Submit
                pnlTrack.Visible = false;
                pnlQuickSubmit.Visible = true;
            }
            else
            {
                // Hide Quick Submit / Show Catalog
                pnlQuickSubmit.Visible = false;
                pnlTrack.Visible = true;
            }

            // Fill DropDownList with Jobs and add All as a selection option
            SHATutil shat = new SHATutil();
            ddJob.DataSource = shat.GetUserJobs(Profile.UserName);
            ddJob.DataTextField = "JobName";
            ddJob.DataValueField = "JobName";
            ddJob.DataBind();
        }
    }

    // Draw the catalog grid with all of the users tracks //
    protected void fillMainGrid() 
    {
        // Fill main grid with composers active tracks
        string cnnString, strSQL;
        cnnString = ConfigurationManager.ConnectionStrings["SmashHausConnectionString"].ConnectionString;

        DataTable dt = new DataTable();

        // Create a connection object and data adapter
        SqlConnection cn = new SqlConnection(cnnString);
        SqlDataAdapter adapter = new SqlDataAdapter();

        strSQL = "SELECT [RecID], [TrackTitle], [Filename], [Description] FROM [metadata] WHERE username = '" + Profile.UserName.ToString() + "'";
        SqlCommand cmd = new SqlCommand(strSQL, cn);

        adapter.SelectCommand = cmd;
        adapter.Fill(dt);

        gvTracks.DataSource = dt;
        gvTracks.DataBind();

        cn.Dispose();
        cmd.Dispose();
        dt.Dispose();
    
    }

    // Update the Playlist grid to reflect what tracks they have added //
    public void UpdatePlaylistGrid()
    {
        // Fill the grid with tracks from the drop down JOB selected
        DataSet dataSet = new DataSet();
        SqlCommand cmd = new SqlCommand("SELECT PlaylistID, TrackTitle, TrackType FROM [Playlists] WHERE username = '" + Profile.UserName.ToString() + "' AND job like '%" + Session["sSelectedJob"] + "%' order by TrackType DESC", new SqlConnection(ConfigurationManager.ConnectionStrings["SmashHausConnectionString"].ConnectionString));
        SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
        dataAdapter.Fill(dataSet, "MYTABLE");
        DataTable dataTable = dataSet.Tables["MYTABLE"];

        gvPlaylist.DataSource = dataTable;
        gvPlaylist.DataBind();
        UpdatePanel1.Update();
    }

    // Store the value in session state for if/when user leaves this page //
    protected void ddJob_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["sSelectedJob"] = ddJob.SelectedValue;
        UpdatePlaylistGrid();
    }


    // Take selected track, store in lookup table, then refresh other grid //
    protected void imgAdd_Click(object sender, CommandEventArgs e)
    {
        if (ddJob.SelectedValue.Trim() == "...Select Job")
        {
            return;
        }

        //Create sql connection and command
        string cnnString;
        cnnString = ConfigurationManager.ConnectionStrings["SmashHausConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(cnnString);
        SqlCommand cmd = new SqlCommand();

        // Get the selected row index - JTS change this 11/23 to only grab the one row - the older versions have the string builder which allows for multiple tracks selections to insert - not necessary here
        int rowIndex = int.Parse(e.CommandArgument.ToString());
        Hashtable oRecord = gvTracks.Rows[rowIndex].ToHashtable() as Hashtable;

        // Either save to Playlist table or move to other grid
        string strUpdate = "INSERT INTO Playlists (username, fkRecID, job, TrackTitle) " +
               "select a.* from (select '" + Profile.UserName + "' as username, " + oRecord["RecID"] + " as fkRecID,'" + ddJob.SelectedValue.ToString().Replace("'", "''") + "' as job, '" + oRecord["TrackTitle"].ToString().Replace("'", "''") + "' as TrackTitle) a " +
               "left join PlayLists b on a.username = b.username and a.job = b.job and a.TrackTitle = b.TrackTitle " +
               "where b.username is null ";

        try
        {
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = strUpdate;
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            string errorMsg = "Error in Updation";
            errorMsg += ex.Message;
            throw new Exception(errorMsg);
        }
        finally
        {
            con.Close();
            UpdatePlaylistGrid();
        }
    }

   
    // Allow user to search their catalog for specific track //
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        // Perform Search and fill grid with results
        string cnnString, strSQL;
        cnnString = ConfigurationManager.ConnectionStrings["SmashHausConnectionString"].ConnectionString;

        // Create a connection object and data adapter
        //MySqlConnection cn = new MySqlConnection(cnnString);
        SqlConnection cn = new SqlConnection(cnnString);

        //MySqlDataAdapter adapter = new MySqlDataAdapter();
        SqlDataAdapter adapter = new SqlDataAdapter();

        strSQL = "SELECT [RecID], [TrackTitle], [Filename], [Description] FROM [metadata] WHERE ([Description] like '%" + txtSearch.Text.Replace("'", "''") + "%' OR [TrackTitle] like '%" + txtSearch.Text.Replace("'", "''") + "%') AND Username like '" + Profile.UserName.ToString() + "%'";

        //MySqlCommand cmd = new MySqlCommand(strSQL, cn);
        SqlCommand cmd = new SqlCommand(strSQL, cn);

        // Create a fill a Dataset
        DataSet ds = new DataSet();
        adapter.SelectCommand = cmd;
        adapter.Fill(ds);

        gvTracks.DataSource = ds;
        gvTracks.DataBind();

        cn.Dispose();
        cmd.Dispose();
        ds.Dispose();
    }

    // Reset the search //
    protected void btnReset_Click(object sender, EventArgs e)
    {
        txtSearch.Text = " ";
        btnSearch_Click(null, EventArgs.Empty);
    }


    // Allow user to delete a song from their Playlist //
    protected void DeleteRecord(object sender, GridRecordEventArgs e)
    {
        string s = e.Record["PlaylistID"].ToString();

        string strSQL = "DELETE FROM Playlists where PlaylistID = " + s;
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SmashHausConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand();

        try
        {
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = strSQL;
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            UpdatePlaylistGrid();
        }
        catch (SqlException ex)
        {
            string errorMsg = "Error in Updation";
            errorMsg += ex.Message;
            throw new Exception(errorMsg);
        }
        finally
        {
            con.Close();
        }
    }



    // TAB TWO CONTENT //
    protected void lnkUpload_Click(object sender, EventArgs e)
    {
        // FILE UPLOAD BUTTON SUBMITTED   
        OboutFileCollection files = uploadProgress.Files;

        uploadedFiles.Text = "";

        for (int i = 0; i < files.Count; i++)
        {
            OboutPostedFile file = files[i];

            file.SaveAs("C:/inetpub/MusicSearchApp/QuickSubmit_MP3s/" + Path.GetFileName(file.FileName));

            if (uploadedFiles.Text.Length == 0)
            {
                uploadedFiles.Text += "<b>Successfully uploaded file</b><table border=0 cellspacing=0>";
                uploadedFiles.Text += "<tr>";
                uploadedFiles.Text += "<td class='option2'>" + Path.GetFileName(file.FileName) + "</td>";
                uploadedFiles.Text += "<td style='font:11px Verdana;'>&nbsp;&nbsp;" + file.ContentLength.ToString() + " bytes</td>";
                uploadedFiles.Text += "<td class='option2'>&nbsp;&nbsp;(" + file.ContentType + ")</td>";
                uploadedFiles.Text += "</tr></table> <br><a href='SubmitForJob.aspx?type=qs'>Submit the Track to this Job</href>";

                // Insert into Playlist Table

                string cnnString = ConfigurationManager.ConnectionStrings["SmashHausConnectionString"].ConnectionString;
                SqlConnection cn = new SqlConnection(cnnString);

                string strSQL = "INSERT INTO Playlists (username, job, TrackTitle, TrackType) " +
                       "VALUES ('" + Profile.UserName + "', '" + ddJob.SelectedValue.ToString().Replace("'", "''") + "', '" + Path.GetFileName(file.FileName).ToString().Replace("'", "''") + "', 'MP3')";
                cn.Open();

                try
                {
                    SqlCommand cmdIns = new SqlCommand(strSQL, cn);
                    cmdIns.ExecuteNonQuery();
                    cmdIns.Dispose();
                    cmdIns = null;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString(), ex);
                }
                finally
                {
                    cn.Close();
                }
            }
        }

        UpdatePlaylistGrid();
    }

}

Open in new window

Vikram Singh Saini

I was talking about how the stuff works on server side by Asp.Net Engine in sequence so... However your requirements are different ... sorry for that.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
MajorBigDeal

Something like this:

 private void InitializeComponent()
        {
            this.PreRender += new System.EventHandler(this.Page_PreRender);
        }

private void Page_PreRender(object sender, EventArgs e)
        {
           // button event already done - but you can still do more stuff here
        }

ASKER CERTIFIED SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
maymounlb

to prevent some of the cde of the page load to run when button  is clicked use this syntax

if (!IsPostBack)
{
//put here the code that you dont want to run when the button is clicked
}