Dropdownlist loses selection after auto refresh - c#

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>

Related

Paging Selected Index Causes DataGrid Refresh

I am making a web page with asp.net, the problem has to be with a asp:datagrid and its page index changing event. The records are displaying and paging correctly but after making a filter and reduce its grid content and trigger the page index again, the grid refreshes and came back all the other records.
This is my PageLoad()
if (!IsPostBack)
{
txtDate1.Attributes.Add("placeholder", "Enter Start Date DD//MM//YY");
txtDate2.Attributes.Add("placeholder", "Enter End Date DD//MM//YY");
this.bindgrid();
}
else
this.bindgridfilter(txtDate1.Text, txtDate2.Text);
My bindGridsmethods()
private void bindgrid()
{
ds = Classes.DBMethods.ShowRecords();
grdRecords.DataSource = ds.Tables[0];
grdRecords.DataBind();
}
private void bindgridfilter(string date1, string date2)
{
dsf = Classes.DBMethods.SearchBetweenDates(date1,date2);
grdRecords.DataSource = dsf.Tables[0];
grdRecords.DataBind();
}
My PageIndexChanging Event
protected void grdRecords_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdRecords.PageIndex = e.NewPageIndex;
grdRecords.DataBind();
}
And my FilterButton Click()
protected void Filter_Click(object sender, EventArgs e)
{
grdRecords.DataSource = null;
bindgridfilter(txtDate1.Text, txtDate2.Text);
}
Now it does the opposite it disappear the grid after making a change of page without a filter, and if it applies a filter now the pagination works correctly
In most web pages, just setting up a drop down list, a grid view, or whatever?
You ONLY want to bind and load the drop down list, or gridview ONE time.
If you re-beind, and re-load the control AGAIN with data, then you will lose your settings.
So, 99% of the time, you want to do such loading ONLY one time,and ONLY on the first page load. Hence, your page load event needs to be this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtDate1.Attributes.Add("placeholder", "Enter Start Date DD//MM//YY");
txtDate2.Attributes.Add("placeholder", "Enter End Date DD//MM//YY");
bindgrid();
}
}
So, now when a button is clicked, or say gv selected index changes, or whatever? Then the information can be used.
If you rebind on each post back, then a gv, or even a simple drop down list will lose its values - hence ONLY load and bind your controls on first "real" page load as per above.
Page load fires EACH time and for each post back. So, any button click or whatever? The page load event will run again. Hence, your general setup code, startup code, and code to load up things like a drop down list, or gridview?
You need to have a if (!IsPostBack) code stub. The last 200 web pages I have created - everyone has such a code stub, and you really for all purposes can't build a working web page without this "setup" or "first load" code stub. If you re-load or re-setup your controls each time, then anything the user enters or does with such controls will be lost.
Of course YOUR buttons etc. and code can and will re-load the grid, but since the page load fires every time with all and any button click (any post-back), then that re-load code will also re-fire, and you don't want that to occur.
Is it correct? PageLoad()
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtDate1.Attributes.Add("placeholder", "Enter Start Date DD//MM//YY");
txtDate2.Attributes.Add("placeholder", "Enter End Date DD//MM//YY");
this.bindgrid();
}
}
PageIndex Event
protected void grdRecords_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
grdRecords.PageIndex = e.NewPageIndex;
if (txtDate1.Text == "" & txtDate2.Text == "")
{
bindgrid();
}
else
this.bindgridfilter(txtDate1.Text, txtDate2.Text);
}

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.

linkbuttons postback before executing click event code?

I am trying to add a basic switch to my site in order to switch between static and responsive layouts.
I have two linkbuttons at the bottom of my page:
<div id="toggleView">
<asp:linkbutton ID="lbtnMobile" runat="server" Visible="false">Switch to Mobile site</asp:linkbutton>
<asp:linkbutton ID="lbtnFull" runat="server" >Switch to Full site</asp:linkbutton>
</div>
They both have a very similar OnClick event.
protected void lbtnFull_Click(object sender, EventArgs e)
{
c.ViewChange = true;
Session["Customer"] = c;
}
protected void lbtnMobile_Click(object sender, EventArgs e)
{
c.ViewChange = false;
Session["Customer"] = c;
}
The events should set a boolean in a class file (User.vb) between true or false and then save the session, on postback the Page_Load event is supposed to read this boolean and use it to adjust the Viewport meta tag:
protected void Page_Load(object sender, System.EventArgs e)
{
//Other Stuff in here, irrelevant to current question
HtmlMeta view = new HtmlMeta();
view.Name = "viewport";
if (c.ViewChange = false)
{
view.Content = "width=device-width, initial-scale=1";
lbtnFull.Visible = true;
lbtnMobile.Visible = false;
}
else
{
view.Content = "width=1040px, initial-scale=1";
lbtnFull.Visible = false;
lbtnMobile.Visible = true;
}
MetaPlaceHolder.Controls.Add(view);
}
However, when I click on the "Switch to Full Site" linkbutton, the page will postback but nothing will have changed. Does the postback get triggered too early somehow?
The page load event will happen BEFORE your click event. Reference this here.
This means your check for the ViewChange will happen before you set it in the OnClick handler.
You should change
if (c.ViewChange = false)
to
if (c.ViewChange == false)
for something to happen. But I think it won't be what you expect. Because page_load is executed before click event. You may move some code from page_load to click event handlers.
When ever you postback the Page_Load always get called. So, the code mentioned inside Page_Load would always get executed.
protected void Page_Load(object sender, System.EventArgs e)
{
... All your mentioned code will be executed.
}
Therefore, you won't find any change in your HTML page currently viewed in a browser because at postback initial content also got executed. You need to wrap your content inside !IsPostBack to make it work properly.
Thus, modify you code in following way.
protected void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostback)
{
... All your mentioned code will be executed during normal load.
}
}
Also, you need to add some extra code in LinkButton click event i.e. what to show and what to hide.
Firstly your implementation in the Page_Load isn't very clear.
Nevertheless this is what I recommend, from what I've understod:
As the page load will get executed before the post-back event like the buton or link click, you need persist the value of the class object
Make a protected property of type of your class (where you store/manage the ViewChange atribute)
The property should internally (in the get & set), hold/persist the value in session/viewstate (similar to what you've written)
The setting and reading should only be by referring the property directly (and not how you've done the click-event)
On clicking of the button and post setting the new value, you will have to redirect to the same page, as only then the Page_Load event will get the new boolean value that you've just changed in the click-event; (Page_Load occurs befoer the any other post-back event)
An alternative to the fresh redirection is that, you could make a function that has the view changing logic (as depicted in your Page_Load code), and this function should be called on your button/link click event (post boolean value change) and also in the Page_Load event, but within the "!IsPostBack" block
Hope this helps you.

when I every refresh page load button_click events run too

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>

How to Refresh GridView after closing down Dialog in ASP .NET

I have a main page with a Gridview that shows data from a Database. In the gridview there is a button, when this button is clicked a Dialog will appear allowing u to edit the selected row. The dialog is created as an aspx class. When i edit the data and close down the dialog i want to refresh my GridView on the Main page so the edited data is represented. How can i do this?
my code for editing the data and closing down the dialog is this:
protected void editButton_Click(object sender, EventArgs e)
{
string alias = Request.QueryString["alias"];
string custid = Request.QueryString["custid"];
controller.EditDeliveries(custid, alias, tdaysField.Text, thoursField.Text, ttypeField.Text, pdaysField.Text, phoursField.Text, ptypeField.Text);
ClientScript.RegisterClientScriptBlock(GetType(), "onUpload", "<script type='text/javascript'> window.close();</script>");
}
Can anyone help ?
And if u need to see more code please tell me.
Just set your datasource again and rebind it in the postback
gvMyGrid.DataSource = myData; //Fresh from the database
gvMyGrid.DataBind(); //Bam, fresh data
Edit: Oh and if it's another Control that is the source of the postback, you can use a Bubble Event to trigger the refresh.
Second Edit: To have the Dialog Page tell the Main Page to update that grid:
RaiseBubbleEvent(this, new CommandEventArgs("DataUpdated", "This could be null, or I could be a message to let the user know things are updated"));
Then on your main Page
protected override bool OnBubbleEvent(object sender, EventArgs e)
{
if (e is CommandEventArgs)
{
var args = (CommandEventArgs)e;
//Could use args.CommandArgument here
switch(args.CommandName)
{
case "DataUpdated":
gvMyGrid.DataSource = myData;
gvMyGrid.DataBind();
return true; //Handled the event LIKE A BOSS
}
}
return false; //I didn't handle this event
}

Categories