when I every refresh page load button_click events run too - c#

I have code Page_Load and btnGonder_Click.I records the some data to database when I click the btnGonder.And I get and show data in the datalist the code which inside the page_load.The problem is that When I every refresh the page,it runs btn_Gonder_Click events and so it records the same data to database.my code is below.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Cevap cevaplar = new Cevap();
int soru_id = Convert.ToInt32(Request.QueryString["Soru_Id"]);
cevaplar.soru_id = soru_id;
DataTable dtcvp = new DataTable();
dtcvp = cevaplar.Cevaplarive_CevapVerenleri_Getir();
datalistcevaplar.DataSource = dtcvp;
datalistcevaplar.DataBind();
}
}
protected void btnGonder_Click(object sender, EventArgs e)
{
Users kullanicim = new Users();
HttpCookie bilgiler = Request.Cookies["Kullanicicookie"];
kullanicim.mail = bilgiler["mail"];
int donenkullaniciid = kullanicim.Kullanici_Id_Donder();
cevaplar.cvpveren_id = donenkullaniciid;
Sorular sorular = new Sorular();
sorular.Cevap_Sayisi_Artir(soru_id);
bool durum = cevaplar.Cevap_Ekle();
if (durum)
{
lblDurum.Text = "Cevabınız Eklenmiştir";
}
else
{
lblDurum.Text = "Cevabınız Eklenmemiştir";
}
DataTable dtcvp = new DataTable();
dtcvp = cevaplar.Cevaplarive_CevapVerenleri_Getir();
datalistcevaplar.DataSource = dtcvp;
datalistcevaplar.DataBind();
}

Page refresh re-fires the same event which has caused the previous postback , so if you refresh the page after clicking the button then button click event will fire. Now to avoid that you have gor multiple solutions. see here

Use this.IsPostBack inside btnGonder_Click() to check the status of submission and return

If you don't want to resubmit the page on refresh then from btnGonder_Click you need to redirect to the same page instead of directly binding data. As this is the basic problem with the Asp.net application.
Do Response.Redirect and pass the name of the page.

If you have already clicked on a button which caused a post back. Next onwards pressing F5, the browser will ask you RESEND which means click the button again. This is normal browser behaviour

Basically you need a workaround to check if it is a page refresh or an actual button click. You can do as below:
The key here is ViewState["IsPageRefresh"] & Session["IsPageRefresh"]. Note that ViewState needs to be enabled on the page for this to work; if ViewState is not enabled then a hidden field may be used.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["IsPageRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["IsPageRefresh"] = Session["IsPageRefresh"];
}
protected void btnPost_Click(object sender, EventArgs e)
{
if (Session["IsPageRefresh"].ToString() == ViewState["IsPageRefresh"].ToString())
{
//Put your database INSERT code here
Session["IsPageRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
}
One simple trick but may be not a standard practice I too agree is below:
Don’t disable the button in the server side. After the page has finished loading the button works as usual.
<head runat="server">
<title></title>
<script type="text/javascript">
function checkButton() {
var btn = document.getElementById("btnGonder");
btn.disabled = true;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnGonder" runat="server" onclick="btnGonder_Click"
OnClientClick="checkButton();" />
</div>
</form>
</body>

Related

Dropdownlist loses selection after auto refresh

i have a dropdownlist that once i choose a selection then the correct info displays in my gridview... Now with my app, the app must refresh after 10 seconds due to the nature of my app... But after the first refresh my selection clears and goes back to the default selection..
I understand what is happening i just cant figure out how to change this.. I have enabled viewstate and autopostback to my dropdownlist but after each postback it is still not getting my last selection... I understand after the postback that everything is saved, but how can i save my selection in view state.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (ddl.Items.Count == 0)
{
BindDropDownList();
}
BizManager mgr = new BizManager();
mgr.CalcShiftPeriod();
_ShiftStart = mgr.Shiftstart;
_ShiftEnd = mgr.Shiftend;
//RefreshLabeldata(214, DateTime.TryParseExact("2016-06-06," DateTime.TryParseExact("2016 - 06 - 06"));
RefreshData(ProductId,
_ShiftStart,
_ShiftEnd);
}
}
public void Dropdownlist1_SelectedIndexChanged(object sender, EventArgs e) //this fires after a DDL selection
{
ddl.EnableViewState = true;
RefreshData(ProductId, _ShiftStart, _ShiftEnd);
}
I have a meta refresh to refresh the page
<head>
<meta http-equiv="refresh" content="10" > <%--refreshes after 10 seconds --%>
Hey i just wanted to give you a heads up. I managed to find a solution... Adding javascript in the head of the markup.. As below.
<script>
window.setTimeout('document.forms[0].submit()', 5000); //refresh the page (without losing state)
</script>

How to prevent back button after LOGIN in asp.net?

I have 2 pages home.aspx and admin.aspx
After successfully logging into admin.aspx when i click back button of browser, it does redirect to home.aspx but that i don't want.
I am checking session variable persistence on home.aspx but for some reason its not working!!
Here's the code
home.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Session["aname"] != null)//should work as session will not be null!
{
Response.Redirect("admin.aspx");
}
} //.....some code..after this
if (dt.Rows.Count != 0)
{
Session["aname"] = TextBox11.Text;
Response.Redirect("admin.aspx");
}
admin.aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["aname"] == null)
{
Response.Redirect("home.aspx");
}
} //some code after this..
protected void logoutbutton_Click(object sender, EventArgs e)
{
Session["aname"] = null;
Session.Abandon();
Session.Clear();
Response.Redirect("home.aspx");
}
NOTE:(things working fine)
1.login working sucessfully
2.logout working sucessfully
3.back button is disabled once loggedout(not going on admin.aspx)
Issue:
When logged in i.e. on admin.aspx ,on clicking back button it redirects to home.aspx which i don't want. i expect it to remain on same admin.aspx
ok.. finally trying all your solutions..this code worked on adding in my masterpage (in head tags)
<script type = "text/javascript" >
function preventBack(){window.history.forward();}
setTimeout("preventBack()", 0);
window.onunload=function(){null};
</script>
full details on this page
You can push the Window History forward to prevent the back button. This has work for me in most cases. Include this JavaScript on your Admin.aspx page.
$(function() {
window.history.forward();
});

DevExpress AspxSpreadsheet Open or Document.LoadDocument method is not working correctly

I need any point of view around this issue from any devexpress developer or anybody who could know about it.
I have this two methods:
The first one gets data from a cache variable and loads it into the spreadsheet document
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
documentId = (String)Session["id"];
Spreadsheet.Open(documentId, DocumentFormat.Xlsx, () =>
{
return (byte[])Cache[documentId];
});
Cache.Remove(documentId);
Session.Remove("id");
}
}
And I have this other method for the Upload event where I get the data from the file and load it into the spreadsheet document
protected void UploadControl_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
fileContent = e.UploadedFile.FileBytes;
documentFormat = GetFileExtension(e.UploadedFile.FileName);
documentId = Guid.NewGuid().ToString();
if (documentFormat != DocumentFormat.Undefined)
{
Spreadsheet.Open(documentId, documentFormat, () =>
{
return fileContent;
});
}
}
}
The Page_Load Spreadsheet.Open function works just fine.
The other one in UploadControl_FileUploadComplete doesn't.
The page does not postback or refresh after or before the upload event, but just comes through the UploadControl_FileUploadComplete event code and execute it.
Any comment or workaround on this will be helpful
ASPxUploadControl uploads files on callbacks. So, other controls can be updated on ASPxUploadControl's callback. You need to handle the client-side FileUploadComplete event and perform a callback on ASPxSpreadsheet to open an uploaded file. To perform a callback, use the ASPxClientSpreadsheet.PerformCallback method. Then, on your server, handle the ASPxSpreadsheet.Callback event to open your document.
<form id="form1" runat="server">
<div>
<dx:ASPxSpreadsheet ID="ASPxSpreadsheet1" ClientInstanceName="Spreadsheet1" runat="server" WorkDirectory="~/App_Data/WorkDirectory" OnCallback="ASPxSpreadsheet1_Callback"></dx:ASPxSpreadsheet>
<dx:ASPxUploadControl ID="ASPxUploadControl1" runat="server" UploadMode="Auto" Width="280px" OnFileUploadComplete="ASPxUploadControl1_FileUploadComplete" ShowUploadButton="True">
<ClientSideEvents FileUploadComplete="function(s, e) { OpenDocument(e.callbackData); }" />
</dx:ASPxUploadControl>
</div>
</form>
const string UploadDirectory = "~/UploadedFiles/";
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e) {
if (e.IsValid) {
string resultExtension = Path.GetExtension(e.UploadedFile.FileName);
string resultFileName = Path.ChangeExtension(Path.GetRandomFileName(), resultExtension);
string resultFileUrl = UploadDirectory + resultFileName;
string resultFilePath = MapPath(resultFileUrl);
e.UploadedFile.SaveAs(resultFilePath);
e.CallbackData = resultFilePath;
}
}
protected void ASPxSpreadsheet1_Callback(object sender, DevExpress.Web.CallbackEventArgsBase e) {
ASPxSpreadsheet1.Open(e.Parameter);
}
<script type="text/javascript">
function OpenDocument(data) {
debugger
Spreadsheet1.PerformCallback(data);
}
</script>

How can I make sure the textchanged event of a textbox is fired before the click event of a button?

I have textboxes and a button.
The button uses a value which is manipulated by the textbox textchanged event.
I don't want the button click event to be fired before the value is changed by the textbox changed event.
void tprice_TextChanged(object sender, EventArgs e) {
idtextbox tsender = (idtextbox)sender;
decimal value = 0;
decimal.TryParse(tsender.Text, out value);
if (area_updates.ContainsKey(tsender.id)) { area_updates[tsender.id].price = value; }
else { area_updates.Add(tsender.id, new area_update(tsender.id) { price = value }); }
Session["area_updates"] = area_updates;
}
protected void bsave_Click(object sender, EventArgs e) {
}
Afaik there is no way to ensure the event order TextChanged->ButtonClick.
You should use a different approach.
Move the TextChanged logic into the ButtonClick event or
Make the TextBox AutoPostBack=true, but this requires an additional postback
So i would suggest to put the logic into the ButtonClick- and remove the TextChanged event.
EDIT: As per another comment you made, if your textboxes are added and removed programatically you could also create a custom user control with your button and textbox, and implement this logic, then programatically add that user control. This is so one button and textbox will be related to each other and not know of others. I'm not sure of the context in which you want to do this, so this approach may not be the best.
Use a textboxIsDirty flag, which you set and unset in the two event handlers.
private bool tpriceIsDirty = false;
void tprice_TextChanged(object sender, EventArgs e) {
tpriceIsDirty = true;
// Do work
}
protected void bsave_Click(object sender, EventArgs e) {
if (tpriceIsDirty)
{
tpriceIsDirty = false;
// Do work
}
}
As suggested in another answer, I would also do the current logic you have in the TextChanged method in the Click method. However, you can bind the tpriceIsDirty flag to the bsave.Enabled property to disable the button altogether if the textbox remains unchanged. Its nicer from a UX perspective. :)
Edit: as per a comment you made, you can also add and remove event handlers on the fly. A variation of this approach may be beneficial to you.
void tprice_TextChanged(object sender, EventArgs e) {
if (bsave.Click == null)
{
bsave.Click += bsave_Click;
}
....
}
protected void bsave_Click(object sender, EventArgs e) {
bsave.Click = null;
}
Yes it's possible ... just have a look on below solution .. It's basically a trick created using javascript but enough powerful ..
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function EnsureNoSubmit(txt) {
//alert('Ensured no submit');//test cases
document.getElementById('<%=hdn.ClientID%>').value = false;
}
function isOkToSubmit() {
var needSubmit = document.getElementById('<%=hdn.ClientID%>').value;
//if (needSubmit != '') {alert('No Submit now');}else {alert('Ok with Submit');}//test cases
return needSubmit == '';
}
function MakeSureSubmit() {
//alert('no submit revoked');//test cases
document.getElementById('<%=hdn.ClientID%>').value = '';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HiddenField runat="server" ID="hdn" />
<asp:TextBox AutoPostBack="true" runat="server" ID="txt" onchange="EnsureNoSubmit();" OnTextChanged="txt_TextChanged"></asp:TextBox>
<asp:Button Text="Click Me" ID="btnClickMe" OnClientClick="return isOkToSubmit();" OnClick="btnClickMe_Click" runat="server" />
</div>
</form>
</body>
</html>
And on code behind side add only one line
protected void txt_TextChanged(object sender, EventArgs e)
{
//Your code is here
Page.ClientScript.RegisterStartupScript(this.GetType(),"Anything","MakeSureSubmit();",true);
}
It will work!!
Enable the Save button's CausesValidation option.
Call the focused editor's DoValidate method.
Call the form's ValidateChildren method.
https://msdn.microsoft.com/de-de/library/ms158374(v=vs.110).aspx

Viewstate not working certain cases when Control Enable=false TextBox looses value

I found an issue in some of my code and can't figure out the reason why. I'm using .Net 4.5. Can anyone please tell me the difference between these two cases? I tried a few different things such javascript to disable via Page.ClientScript or on the body onload event but I'm not getting what I want (TextBox2 is "" and TextBox1 is "Hello, TextBox1"). When I comment out tmp.Enable = false everything is fine. I'd like to be able to disable both controls but still access the Text value. Works fine for "TextBox1" but not "tmp" aka "TextBox2".
The reason for !IsPostBack and TextBox2 being created during the Page_Load is because I'm dynamically creating X number of controls and setting their value from a datareader. they can then be modified by the user and saved to the table. There must be a way!
This post sounds like my problem but I'm getting different results than them.
ASP.Net ViewState doesn't work when Control become Enable=False
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function t() {
document.getElementById("TextBox1").disabled = true;
document.getElementById("TextBox2").disabled = true;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel runat="server" ID="Panel1">
<asp:TextBox runat="server" ID="TextBox1"></asp:TextBox>
<asp:Button runat="server" ID="button1" OnClick="button1_Click" />
</asp:Panel>
</div>
</form>
</body>
</html>
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) { TextBox1.Text = "Hello, TextBox1"; }
TextBox1.Enabled = false;
TextBox tmp = new TextBox();
tmp.ID = "TextBox2";
if (!IsPostBack) { tmp.Text = "Hello, TextBox2"; }
tmp.Enabled = false;
Panel1.Controls.Add(tmp);
}
protected void button1_Click(object sender, EventArgs e)
{
TextBox tmp = ((TextBox)Page.FindControl("TextBox2"));
if(tmp != null)
{
tmp.Text.ToString();
}
TextBox1.Text.ToString();
}
}
UPDATE:
Per haraman's suggestion I was able to get it working by making the following changes:
protected void Page_PreInit(object sender, EventArgs e)
{
TextBox tmp = new TextBox();
tmp.ID = "TextBox2";
Panel1.Controls.Add(tmp);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) { TextBox1.Text = "Hello, TextBox1"; }
TextBox1.Enabled = false;
if (!IsPostBack) { ((TextBox)Page.FindControl("TextBox2")).Text = "Hello, TextBox2"; }
((TextBox)Page.FindControl("TextBox2")).Enabled = false;
}
protected void button1_Click(object sender, EventArgs e)
{
TextBox tmp = ((TextBox)Page.FindControl("TextBox2"));
if (tmp != null)
{
tmp.Text.ToString();
}
TextBox1.Text.ToString();
}
You should consider using ReadOnly = true instead of Enabled = false.
Values for disabled form elements are NOT passed to the processor method. For more specific details refer disabled-vs-readonly-form-fields/
EDIT: Addition with regard to your code
Created a test case with your code and found that I just misread your code. Here is what is happening in your code:
You create a new TextBox (tmp) on every PostBack.
tmp is recreated (But TextBox1 is already there and NOT recreated)
You do NOT assign value to tmp on every PostBack
This means there is no text in tmp (TextBox1 NOT being recreated, retains its text)
More specific details can be found in the answer given by R.C in this SO post dynamically-created-controls-losing-data-after-postback
A practical approach to the same can be found in this post ASPNet-Dynamic-Controls-ViewState-Retain-state-for-dynamically-created-controls-on-PostBack
try using Read Only Property????
Read Only
In the context of a TextBox, readonly allows the user to set focus to
and select and copy the text but not modify it. A disabled TextBox
does not allow any interaction whatsoever.
Use ReadOnly when you have data that you want the user to see and
copy, but not modify. Use a disabled textbox, when the data you are
displaying is not applicable in for the current state of a dialog or
window.
Enabled:
Gets or sets a value indicating whether the control can respond to
user interaction.

Categories