ASP.NET C#,需要按两次按钮才能使某事发生
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/297217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET C#, need to press a button twice to make something happen
提问by
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,
我有一个Web应用程序,问题是第一次单击时标签中的文本不会更新,我需要单击按钮两次,我调试代码,发现标签直到之后才收到数据第二次点击,
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;
}
采纳答案by HymanCorn
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.
要非常清楚。按钮单击事件发生在 Page_Load 事件之后,这意味着过滤不会应用于第一次回发。它已在第二次回发时更新,您会看到过滤。使代码工作的最简单更改是将 Page_Load 事件中的所有代码移动到 OnPreRender 中,以便在按钮单击事件之后重新加载。
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:
然而,更简洁的解决方案可能是将它移到 LoadData 函数中,并在它不是回发时在 PageLoad 上调用它,并在更新过滤器后在按钮单击事件上调用它。这将防止在不需要重新加载数据的任何回发页面周期上调用数据库:
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.
对于初出茅庐的 ASP.Net 开发人员,最后一条快速建议是彻底了解页面生命周期。了解页面上的事件顺序至关重要。祝你好运。
回答by Dillie-O
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.
在您的 Page_Load 方法中,这意味着每次加载页面时都会发生数据绑定,这很可能会导致您的问题。我建议将其添加到代码中,看看它是否能解决问题。
回答by EndangeredMassa
The button click event handlers happen AFTER Page_Load. Try using Page_LoadComplete instead.
按钮单击事件处理程序在 Page_Load 之后发生。尝试改用 Page_LoadComplete。
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.
因此,在您的代码中,一旦单击按钮,page_load 事件将触发并设置数据,然后 btnClick 事件触发并更改数据。但是,数据已经以旧形式绑定。这就是为什么它需要点击 2 次才能工作。
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.
如果您将相同的 page_load 代码放入 page_loadcomplete 事件中,它将在 btnClick 事件之后发生。这应该会产生预期的结果。
回答by Jonathan S.
Microsoft's overview of the Page Life Cyclemay be helpful in understanding the flow (and resolving your issue).
Microsoft 对页面生命周期的概述可能有助于理解流程(并解决您的问题)。
回答by HymanCorn
HymanCom, 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.
HymanCom,解决方案奏效了!谢谢你。我将研究页面生命周期。我必须补充一点,我只有软件开发经验,我今年秋天才刚刚开始 Web 开发。
回答by Woodsie
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.
我被困在这个问题上大约一个星期。最后,我将Button_Click
事件的代码放在事件中,TextChanged
并且它起作用了。按下按钮会使焦点离开,TextBox
以便在Button_click
事件不发生时触发事件。很笨拙。我不喜欢。
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
我发现了一篇有趣的文章,但实际上对我不起作用,但我很高兴我还是读了它:Enter 和按钮单击事件
That might work in other situations.
这可能适用于其他情况。
回答by Les Smith
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.
ASP.Net 有时会做一些非常奇怪的事情。我今天遇到了同样的问题。我发现我在 TextBox 上放了一个 AutoPostBack = "true ,即使它没有达到我想要的效果,我忘了把 AutoPostBack 从标记中取出来。当我点击同一表格行中的一个按钮时,第一次点击导致两次回发,但没有触发按钮事件。第二次点击按钮时,按钮点击事件触发。当我从标记中发现无关的 AutoPostBack 时,按钮事件在第一次点击时开始触发。有人会认为除了按钮单击事件引用了文本框的内容之外,文本框与按钮无关。
回答by Pic Mickael
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.
我在我的页面上遇到了同样的问题。每次我都必须点击两次才能让它工作。这是由于某些文本框和下拉列表将 autopostback 设置为 true 造成的。一旦我删除了自动回发甚至变得顺利并且单击正确触发。
回答by Minh
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,
});
}
回答by PKatona
I had this problem because I was using "Server.Transfer" to go between pages. When I changed to "Response.Redirect" the problem was solved.
我遇到这个问题是因为我使用“Server.Transfer”在页面之间切换。当我改为“Response.Redirect”时,问题就解决了。