Andre Nilsen
Andre Nilsen

Reputation:

ASP.NET C#, need to press a button twice to make something happen

I got a web application, the problem is that the text in the label will not update on the first click, I need to click the button twice, I debugged to code, and I found out that the label does not recive the data until after the second click,

Here is my code:

System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();
System.Data.SqlClient.SqlConnection connection;
string CommandText;
string game;
string modtype;
bool filter;
protected void Page_Load(object sender, EventArgs e)
{

    labDownloadList.Text = null;

    //Session variables:
    if (Session["Game"] != null)
    {
        game = Convert.ToString(Session["Game"]);
    }
    if (Session["ModType"] != null)
    {
        modtype = Convert.ToString(Session["ModType"]);
    }
    if (Session["FilterBool"] != null)
    {
        filter = Convert.ToBoolean(Session["FilterBool"]);
    }
    string ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\inetpub\\wwwroot\\stian\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True";
    connection = new System.Data.SqlClient.SqlConnection(ConnectionString);
    System.Data.SqlClient.SqlDataReader reader;
    command = connection.CreateCommand();
    connection.Open();
    CommandText = "SELECT * FROM Command";
    if (filter)
    {
        CommandText = "SELECT * FROM Command WHERE Game='" + game + "' AND Type='" + modtype + "'";
    }
    command.CommandText = CommandText;
    reader = command.ExecuteReader();
    labDownloadList.Text = "";
    while (reader.Read())
    {
        string game = reader.GetString(1);
        string author = reader.GetString(2);
        string downloadlink = reader.GetString(3);
        string size = reader.GetString(4);
        string description = reader.GetString(5);
        string version = reader.GetString(6);
        string screenshotlink = reader.GetString(7);
        Int64 AmountDownloaded = reader.GetInt64(8);

        labDownloadList.Text += "Game: " + game + "<br>";
        labDownloadList.Text += "Author: " + author + "<br>";
        labDownloadList.Text += "Size: " + size + "<br>";
        labDownloadList.Text += "Description: " + description + "<br>";
        labDownloadList.Text += "Version: " + version + "<br>";
        labDownloadList.Text += "<img src='" + screenshotlink + " /><br>";
        labDownloadList.Text += "Downloaded: " + AmountDownloaded + " times<br><hr>";
        labDownloadList.Text += "<a href='" + downloadlink + "'>Download</a><br>";
    }
}

protected void Page_UnLoad(object sender, EventArgs e)
{
    Session["Game"] = game;
    Session["ModType"] = modtype;
    Session["FilterBool"] = filter;
    connection.Close();
}

protected void btnFilter_Click(object sender, EventArgs e)
{
    game = lstGames.SelectedValue;
    modtype = lstTypeMod.SelectedValue;
    filter = true;
}

Upvotes: 9

Views: 26313

Answers (11)

Bruce Patin
Bruce Patin

Reputation: 355

After converting a VB project to C#, I had the double click event problem. Discovered that the converter converted the code behind but not the ascx and aspx page code, which still said language="vb". Converting that bit by bit to C# then stating language="cs" fixed the problem.

Upvotes: 0

PKatona
PKatona

Reputation: 639

I had this problem because I was using "Server.Transfer" to go between pages. When I changed to "Response.Redirect" the problem was solved.

Upvotes: 0

Minh
Minh

Reputation: 1

I don't know well about this but this trick work for me :

function pageLoad(sender, args) {
    $(document).ready(function () {
        //your stuff
    });
    $(":button").each(function() {
        $(this).click();
        //this is a trick;  click one when page load,
    });
}

Upvotes: 0

Pic Mickael
Pic Mickael

Reputation: 1274

I had the same problem on my page. Each time I had to click twice to get it to work. This was caused by some textbox and dropdownlist having autopostback set to true. Once I removed the autopostback even went smooth and single clicks triggers properly.

Upvotes: 1

Les Smith
Les Smith

Reputation: 1

ASP.Net can do really weird things sometimes. I was having this same problem today. I found that I had put an AutoPostBack = "true on a TextBox and even though it did not work out to do what I wanted, I forgot to take the AutoPostBack out of the markup. When I clicked a button in the same table row, the first click caused two postbacks but did not fire the button event. Upon clicking the button the second time the button click event fired. When I found the extraneous AutoPostBack from the markup, the button event started firing on the first click. One would think that the textbox was in no way connected to the button except that the button click event referenced the contents of the textbox.

Upvotes: 0

Woodsie
Woodsie

Reputation: 1

I was stuck on this for about a week. Finally, I've put the code behind for the Button_Click event in the TextChanged event and it worked. Pressing the button makes the focus leave the TextBox so that event fires when the Button_click event doesn't. Very kludgy. I don't like it.

I came across an interesting article that didn't actually work for me, but I'm glad I read it anyway: Enter and the Button Click Event

That might work in other situations.

Upvotes: 0

Andre Nilsen
Andre Nilsen

Reputation:

JackCom, the solution worked! Thank you. And I will study the page lifecycle. I must add, that I only have experience in software development, I have just started with web development this autumn.

Upvotes: 1

EndangeredMassa
EndangeredMassa

Reputation: 17528

The button click event handlers happen AFTER Page_Load. Try using Page_LoadComplete instead.

So, in your code, once the button is clicked, the page_load event fires and sets the data, then the btnClick event fires and changes the data. But, the data was already bound in it's old form. That's why it takes 2 clicks for it to work.

If you put the same page_load code into the page_loadcomplete event instead, it will happen after the btnClick event. That should produce the desired result.

Upvotes: 6

JackCorn
JackCorn

Reputation: 146

To be very clear. The button click event happens after the Page_Load event meaning that the filtering does not get applied on the first postback. It has been updated on the second postback and you see the filtering. The simplest change to get your code to work is to move all the code in your Page_Load event into OnPreRender so the reload happens after the button click event.

A cleaner solution however is probably to move it into a LoadData function and call that on PageLoad when it is not a postback and also call it on the button click event after updating your filters. That will prevent a call to the database on any postback page cycles that do not need to reload the data:

 
protected void Page_Load(object sender, EventArgs e)
{    
    if (!Page.IsPostBack)
        {   
             LoadData()
        }
}

private void LoadData()
{
    labDownloadList.Text = null;
    //Session variables:    
    if (Session["Game"] != null)
    ...
}

protected void btnFilter_Click(object sender, EventArgs e)
{    
    game = lstGames.SelectedValue;
    modtype = lstTypeMod.SelectedValue;
    filter = true;
    LoadData();
}
 

A last piece of quick advice for a budding ASP.Net developer is to thoroughly learn the page lifecycle. Knowing the sequence of events on a page is essential. Good Luck.

Upvotes: 11

Jonathan S.
Jonathan S.

Reputation: 5877

Microsoft's overview of the Page Life Cycle may be helpful in understanding the flow (and resolving your issue).

Upvotes: 7

Dillie-O
Dillie-O

Reputation: 29755

I'm not seeing the typical

if (!Page.IsPostBack)
{
   ...
}

in your Page_Load method, which means that your datbinding will occur every time the page is loaded, most likely causing your issue. I'd suggest adding that to the code and see if it resolves the issue.

Upvotes: 2

Related Questions