Web Forms :: Saving Variable Value Across PostBack?
Apr 25, 2014i need to save a timestamp byte[] array between page post backs in asp.net webforms and thought having a global variable in a class would work, but it does not?
View 1 Repliesi need to save a timestamp byte[] array between page post backs in asp.net webforms and thought having a global variable in a class would work, but it does not?
View 1 Replies[Code]....
I have a publice variable to be used in the same webpage. when the user click on button 1, it does some process and assign a value to my public variable. After that, the user can click on button 2 which needs the public variable value to function. However I see the value of the public variable is 0 when I click on button 2.
I know this has been asked before, but I feel like I'm losing my way trying to follow the other examples out there. Does anyone see a straightforward solution to my particular problem?
Goal:
Two column Master Page
Left column contains a list of [stuff] (I'm trying a Repeater with LinkButtons)
Right column contains a TabContainer which will add dynamically created tabs when buttons on the left are clicked.
Left side looks like this:
<asp:Repeater
<ItemTemplate>
<asp:LinkButton ID="lbShowReport" runat="server" Text='<%# Eval("Title") %>' CommandName="Select">
</asp:LinkButton>
<asp:HiddenField ID="hfReportID" runat="server" Value='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:Repeater>
I had initially been creating tabs in the LB's OnCommand event, but of course this means that any tab generated by one click is lost if the user clicks another LinkButton.
So I moved the code to create a new tab to the OnInit section of the page and attempted to loop through the RepeaterItems comparing the UniqueId of each LinkButton until I found the one that was clicked using Request.Form["__EVENTTARGET"].
When I tried to loop through the RepeaterItems, however, the count was always 0, and the Repeater would not populate.
So now I am rebinding the Repeater in the Init section on every post-back - this allows me to find the LinkButton that was clicked. I then add the new Tab based on the LB that was clicked like this:
[Code]....
This properly adds new Tabs to the TabContainer using this code:
[Code]....
but I still have the issue where I can only ever have one dynamically created tab in the TabContainer at a time. All of the code above is being executed in OnInit, which I thought would save the tabs during post-backs, but instead this is behaving as tho I was adding the tabs in the OnCommand event of the Link Button...
On my MVC2 web application I have a form that a user can enter dates, times, comments etc for appointments with clients. We then give him the oppertunity to download it as a vCalendar file. So far, on my controller I have the following code (I have just included the string that stored my vCard data) :
[Code]....
I have worked with uploading and downloading binary files within MVC, but working with stuff like this I am totally lost. This code needs to be saved as a .vcs from withing the client's browser. My return value looks something like this :
[Code]....
I need to save data in a datatable on a web page where the user is adding items to order. I know how to create a datatable and add data to it. And I will be binding it to a gridview control. But I do not want to loose the data when the page does a postback. Do I need to save it to a session variable for this? Or will the data stay in the datatable?
I found this code posted online. Is this how I would save it to a session variable and then load it anytime?
Code:
Dim dt As New DataTable()
Session("MyDataTable") = dt
' To retrieve it from session
Dim dt As DataTable = DirectCast(Session("MyDataTable"), DataTable)
I am performing my first steps with ASP.NET for my employment.Yesterday I tried to perform saving a value to a sessionstate variable, but it does not work.I am using C# and want to code in .NET 3.5. [Code]....
The click performs a postback to a second website where the value is to be displayed on a simple label.The value I initialized in the Global.asax is saved to the variable and then read on the second page, but I cannot manipulate it using the textbox and the button on the first page. I just don't get it...I even tried on different machines and different VS editions.
I'm fairly new so I've been learning via examples. The idea of this part of the project is to present a list of items (out of a DB), and when you click on an image that's on the list, it should open a new window with the details. this is the snippet where
I send the variable:
<asp:ImageButton runat="server" ID="imagebutton1" ImageUrl="images/icon_lupa.gif"
I have some textboxes (in an UpdatePanel in a ModalPopup in a User Control) that look like this:
<asp:TextBox ID="exampleTextBox" runat="server" MaxLength="10"
CssClass="datepicker" ReadOnly=true
Text='<%# Bind("ExampleDateField") %>' Width="77px">
</asp:TextBox>
I also have some jQuery (imported from file on the Master page) that hooks up the jQuery DatePickers like so:
function pageLoad() {
$(".datepicker").unbind();
$(".datepicker").datepicker({
changeMonth: true,
changeYear: true,
showOtherMonths: true,
selectOtherMonths: true,
beforeShowDay: $.datepicker.noWeekends,
showOn: 'button',
buttonImage: '../Resources/Images/Calendar_scheduleHS.gif',
buttonImageOnly: true,
buttonText: 'Select a Date'
});
}
The DatePickers appear correctly, even after a postback. The problem is that the value of the textboxes is not changed when a postback occurs. This is very odd since the textbox shows the selected date in the browser. However, the value of the textbox is still the date that the textbox originally had, not the date selected from the datepicker.
I have a calculation in a gridview rowdatabound event that stores a value in a session variable. The problem is that after the page is viewed the first time, the value continues to accumulate each time it is posted back. How can I calculate the value the first time and stop it from continuting to recalculate and add to itself each time the page is reloaded?
View 7 RepliesI have made something like the following code:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Session["loginid"].ToString();
}
protected void delete_click(object sender, EventArgs e)
{
delete("mail1",Session["loginid"]);
}
private int delete(string mailid, string user)
{
System.IO.Directory.Delete(Server.MapPath(@"~files" + user + @"" + mailid), true);
}
When i press the delete button, everything works fine and the folder gets deleted. but after that when page postbacks again then a NullRefrenceException is raised at Label1.Text = Session["loginid"].ToString(); why is it happening...?? When I am not using this Directory.Delete() method everything is working fine and session variables are not set to null. When I traced my application I found that After Directory.Delete() method Session variables were intact and I was able to use those session variables in the processing after Directory.Delete(). But as soon as the page postbacks all session variables are set to null. And this problem doesn't appear when i m not using this delete() method. The folder I m deleting is in my project's folder. I m running this website using Visual Studio.
I have created a composite control with sample details as follows. Basically, the first time on page load the control sets a view state variable and the problem is that on post back (when the button is clicked), the ViewState variable is null. I have researched extensively and I am not able to find a solution. I checked all the Microsoft recommended articles and also from other developers. This approach seem to work for everyone
PS: This code may not work as it is only for illustrative purposes. but this is exactly what i'm doing in my code.
Public class Test : CompositeControl
{
private Button btnTest = new Button();
public string TestViewState[code]....
I got a variable of type System.Drawing.Image and need to convert it to a variable of type byte so I can store the image in the database. Can someone show me how to do that in VB.NET code.
View 2 RepliesNested GridView Control returns "Object variable or With block variable not set" when outer GridView returns rows.
The Nested GridView Control works as long as the outer GridView returns rows, the following code works: [Code]....
Object variable or With block variable not set.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object variable or With block variable not set.
Source Error:
Line 118: If e.Row.RowType = DataControlRowType.DataRow Then
Line 119: Dim myStatus_ID As SqlDataSource = CType(e.Row.FindControl("sqlDeviceStatusAssign"), SqlDataSource)
Line 120: If Not e.Row.DataItem("Status_ID") Is Nothing Then
Line 121: myStatus_ID.SelectParameters(0).DefaultValue = e.Row.DataItem("Status_ID")
Line 122: End If
I have tried checking for IsDbNull and checking to see if a label exists in a given row. This code *If Not e.Row.DataItem("Status_ID") Is Nothing Then* appears to do nothing.Same with the following:
*Dim localLblItemReference As Label = CType(e.Row.FindControl("lblItemReference"), Label)
*If Not localLblItemReference Is Nothing Then
******************************************************************************************
To further clarify my question above, I am looking for a method to detect e.Row.DataItem("Status_ID") is nothing/null due to the outer GridView returning 0 results in a query.I have a (Outer) GridView Control with another GridView Control inside of a template field with it's associated SqlDataSource control.
In the "Protected Sub GridViewReport_RowCreated", I provide the Select Parameter for the associated SqlDataSource with the DataItem row value.When the (Outer) GridView Control does not return any rows, the "e.Row.DataItem("Status_ID")" throws a:
Exception Details: System.NullReferenceException: Object variable or With block variable not set.
I am using three listviews on a page ... the first is always populated ... the other two are sometimes populated I want to total amounts and counts from all three ... so I set up steps in the DataBound events works great when all three listviews are populated the error "Object Variable or With block variable not set." occurs when LV2 or LV3 is not populated I've tried testing DataItem ... Is Nothing but get the failure on the If test instead
View 3 Repliescan we grab a global variable or Session or View State variable in the javascript or using jquery?
I have a web application which uses a session variable to store the logged in userid. If no user is logged in, of course this variable will be empty and the contents displayed on my website are meant for guests. If there is a user logged in, the user specific controls/access/links will then be a displayed.
I am now having issues with my hosting where on shared application pool, the worker recycle is triggered every 90 minutes, this will clear sessions causing all my users to be logged out. I opted for a dedicated application pool, which got worse because I am only allocated 50MB memory limit and if this is reached, the worker recycle is triggered and I lose my sessions again. I have tried as much as possible optimization techniques, e.g. dispose where possible, close connections, disable viewstate for static controls etc but my memory per instance keeps building up from page to page without any signs of improvement. I don't use loops nor store huge objects like bitmaps etc but my sessions are now gone even faster than 90 minutes in shared application pool before.
I have considered using SQL Session State but there isn't a simple guide on using this with MySQL. I am getting desperate and considering using a public variable, a string as a replacement to store logged in user id instead of in a session variable. I am pretty sure this will solve my issue with sessions being recycled but are there any negative consequences of doing this? One problem I can think of is if the user closes the browser, the system will never know that the user is now logged out and this public variable should be nothing. In this scenario, will the GC eventually clear this abandoned public variable.
I'm evaluating two options of accessing a server side data on client side. Little bit confused about the efficiency or may be you can call it as finding best approach to do it.
I need to access a server side data may be an integer value in javascript on client side. I know about two options to do it.Create a public variable or property on server side and set it to javascript variable on client side as below:
var value = eval(<% =value %>);
Create a asp hidden variable and set value in this hidden variable from server side and access it through javascript using document.getElementById().
Which is the best approach and what are the pros and cons?
Possible Duplicate: Use of var keyword in C# Hi, I am pretty new in C#,I would like to know the best practices in declaring variables.I know it is possible to use VAR (explicit declaration) or the DataType when declaring a variable (implicit).
View 3 RepliesI'm am not quite sure why I am getting this error.
Dim numUsers as Integer
Using myConnection as New System.Data.SqlClient.SqlConnection("Data Source=(local);InitialCatalog=dbtest;Integrated Security=True")
Dim queryString As String = "SELECT COUNT(*) AS Num_Of_User FROM tblusers WHERE username=@username AND password=@password"
Using myCommand as New System.Data.SqlClient.SqlCommand(queryString, myConnection)
myConnection.Open
myCommand.Parameters.AddWithValue("@username", requestName)
myCommand.Parameters.AddWithValue("@password", requestPass)
numUsers = myCommand.ExecuteScalar()
End Using
End Using
This error occurs on the first using statment.
have a look at this simple code snippet
[Code]....
Here second declaration of x gives error that "variable 'x' hides a variable in an enclosing block. I wonder why this error is not given for second 'i' variable declared in second for loop?
Since i am declaring second x in a separate for block, why this error is given for variable second x ?
What would be the proper syntax in ASP.NEt 3.5 C# to assign a TextBox value to a temporary or session variable to be manipulated (added, subtracted, multiplied, divided) at different points in the application? I want to add a decimal number to this variable in almost every instance as well.
View 3 RepliesOn my page: a Button1, a ListView1, a Panel1 and inside Panel1 an ImageButton1In the ListView1_PreRender-Event the property Panel1.Visible = false or Panel1.Visible = true is set.1. After first loading of the Page Panel.Visible = false ist set in ListView1_PreRender.2. After the postback click on Button1 the criteria for the visibility of Panel1 are evaluated, thus setting in the ListView_PreRender Panel.Visible = true.
View 3 RepliesI have a script that runs during the Page_Load() event which checks a database table to make sure that the user is still owns the lock on the page. If they no longer own the lock, I disable all the controls on the page and display an
error message.My thinking was that by disabling all controls during Page_Load() I could prevent any PostBack events from occuring. For example, I have a button on the page called "Save and Quit"
Which is better from a performance perspective?
Accessing a Global Application Variable (Application["foo"])
versus
Accessing an AppSetting variable from the web.config
Does .NET Cache the AppSetting variables so that it is not accessing the web.config file with every use?
I have the dataset. in this i am having total 20 tables with huge amount of data..I want use this data over all the page..so where i can keep this data..
before i used viewstate but the viewstate data is render to page every postback ..so this time the page size is increasing(interanlly viewstate is rendered to page)..so performence wise it was very slow..
Now i change my logic insted of viewstate to i used Globel Dataset on Page Level.. now the performence wise better than viewstate..
i used Like shared dsControls as Dataset at top of the page..so every time i use this dataset..
my quesation is session is better or Globel variable is better way use in my situavation..