Saving a value to and reading from the viewstate - c#

I'm not too familiar with .NET, but I want to save a simple value (a number between 1 and 1000, which is the height of a particular div) to the viewstate and retrieve it when the update panel reloads (either in the markup somewhere or with javascript). What is the simplest way to do this?
This page gives me the following code:
string strColor;
if (Page.IsPostBack)
{
// Retrieve and display the property value.
strColor = (string)ViewState["color"];
Response.Write(strColor);
}
else
// Save the property value.
ViewState["color"] = "yellow";
However, I'm not totally clear on where or how to access the example strColor.
Since this is in the code behind, where will Response.Write even spit that code out? I couldn't find it when I tried this code. And how do I use javascript to set that value, instead of setting it in the code behind?

You can simply set the div as a server control as so:
<div id="yourdiv" runat="server" ...
And when the page posts back; simply set it's height by setting its attributes; for example:
yourDiv.Attributes("style","height:"+height_read_from_ViewState+"px;");
Or, you can store the height on the client side, using a Hidden field and reading that hidden field's value on the server side to set the div's height.
<asp:hiddenfield id="hdnHeight" runat="server" />
You set the height in Javascript as so:
function setHeight(value)
{
document.getElementById('<%=hdnHeight.ClientID').value=value;
}
And on post back on server side:
yourDiv.Attributes("style","height:"+hdnHeight.Value+"px;");

I would change strColor to a property and use the viewstate as a backing store for the propery.
public string strColor
{
get
{
return ViewState["strColor"];
}
set
{
ViewState["strColor"] = value;
}
}
And then you would use it like any other property:
if (Page.IsPostBack)
{
// Retrieve and display the property value.
Response.Write(strColor);
}
else
// Save the property value.
strColor = "yellow";

Related

To use hidden field value in another aspx file

In the below code i have a hidden value in sample.ascx and i want to use that value in sample.aspx in its codebehind.pls help me to do this.
Sample.ascx
txthidd.Value = "Hai";
<asp:HiddenField ID="txthidd" runat="server" />
You can create a Public property in your ascx like this
public string txt
{
get
{
return this.txthidd.Value;
}
}
and can access this in aspx like this
string textOnAspx = UC_UserControl.txt;
In the codebehind, you should create a property getting the field:
public string TxtHidText{
get
{
return txthidd.Value;
}
}
Then, you'll reference it per the id, let's say you'll have something like this in ASPX:
<u1:Sample id="SomeSampleContentOfThePage" />
and in codebehind, it will be accessible via
var text = SomeSampleContentOfThePage.TxtHidText;
Note that if you want to set it from the other aspx, you should create a set part as well.

Hidden field value updated but not showing updated value in codebehind?

I am setting the hidden filed value through JavaScript as below
<script lang="JavaScript" type="text/javascript">
function ChangeVal()
{
var elem = document.getElementById("btnDownloadStream");
if (elem.value == "Start")
{
elem.value = "Stop";
document.getElementById('myHiddenInput').value = "1";
}
else
{
document.getElementById('myHiddenInput').value = "0";
elem.value = "Start";
}
}
I am trying to get hidden field value in code behind. My code is
HiddenField myHiddenInput = (HiddenField)Page.FindControl("myHiddenInput");
var val = myHiddenInput.Value;
Before this line I am calling one function which creates and generates the GetResponseStream(). While doing this I am not able to get the value from server controls. Why?
Becuase Changing the value in javascript will not affect the server side value.
if you want to change a server side value from javascript: You can try the following
// Javascript
var myHidden = document.getElementById("<%:myHiddenId.ClientId%>");
myHidden.value = myJSVariable;
Make sure the myHidden is a server control.
Set Runat="server" attribute to your hidden field as shown below :
<input type="hidden" value="" id="myHiddenInput" runat="server" />
Then update your javascript function as shown below :
function ChangeVal() {
var elem = document.getElementById("btnDownloadStream");
if (elem.value == "Start") {
elem.value = "Stop";
document.getElementById('<%=myHiddenInput.ClientID%>').value = "1";
}
else {
document.getElementById('<%=myHiddenInput.ClientID%>').value = "0";
elem.value = "Start";
}
}
now you can directly access your hidden field value in your code behind without using Page.FindControl as mentioned :
var val = this.myHiddenInput.Value;
Update:
One thing I have noticed that your button is server side button and in your javascript you call
var elem = document.getElementById("btnDownloadStream");
I think it should be
var elem = document.getElementById('<%=btnDownloadStream.ClientId%>')
otherwise you will always get the value of else part
Make sure this is not the case.
well #Vishweshwar Kapse is answered your question.
Place your hidden field in update panel and don't forget to add click event of button in trigger.
This also happens in case you use the UpdatePannel in your page. if this is the case then place the HiddenField inside the UpdatePannel and try again.
You forget about ViewState. If you change data in the hidden field using java script code the ViewState do not get this changes and that's why you cannot get the correct value in code behind.
Make sure your hidden field have runat="server" attribute..

Assigning objects within public method

I wish to create a public method on my masterpage, that I can call from within every subpage.
I am trying to wrap my head around how this should be done.
On my subpages I've made this method to fill a panel with an errormessage.
protected void errorMessage (string errorText) {
HtmlGenericControl divTag = new HtmlGenericControl("div");
Panel_Name.Controls.Add(divTag);
divTag.InnerHtml = errorText;
}
Now if I were to make this function public on my masterpage, It wont recognize my Panel as it havent been showed yet. I'm guessing the answer involves FindControl
(Sorry for my rubbish code english)
How should I do this ?
To be fair, for your scenario, I would use a UserControl (.ascx) on your Pages (.aspx).
Then, in the UserControl, have your error message markup, such as:
Code front (ErrorMessage.ascx)
<asp:Panel runat="server" ID="PanelErrorMessage" /> // creates a <div>
Code behind (ErrorMessage.ascx.cs)
public string ErrorMessage
{
get {}
set
{
PanelErrorMessage.Text = value; // sets the panel text (<div>text</div>) to value when property is set
}
}
Use your UserControl on your Page (you'll need to define this as a control tag on your page too with the prefix/suffix):
<myControls:ErrorMessage runat="server" ID="MyErrorControl" />
You can also do this in many places on your page, if you require different errors.
Then, when you have an error, you'll simply do:
MyErrorControl.ErrorMessage = "This is my error message";
Job done!

pass html TextBox Value from User control to aspx page

I am creating a user control where in i have different HTML text boxes and for items like name profession contact etc.
i have a edit and save button for each item. so when i click on the save button i want the value of that text box and update the same in the database . So for this i want to send that value to the ASPX page. but i don't know how to send that value to the ASPX.Also if there is another way to achieve this them please suggest.I am using the three tier architecture.
Thankx
If text box is asp text box or html runat="server" st than you need to expose textbox value as property
public string textData
{
get { return mytextbox.Text; }
set { mytextbox.Text = value; }
}
OR
If you text box is html than make use of Request.QueryString["textboxnameorid"] will provide you data on postback.
if you are using asp.net textbox, you can create public properties in you usercontrol like this
public string Name
{
get { return tbName.Text; }
set { tbName.Text = value; }
}
and this public property can be get set in asp.net page easily..
Regards.

Storing an List<int> in viewstate

I have an aspx page which has the following:
A repeater with a linkbutton in each
The link button has a commandargument of an integer value
A user control
The idea is that when the user clicks on the linkbutton the value of the commandarguement is stored in a List. No problem you may think, however I need the value to be stored in an List in the usercontrol, not in the ASPX page. The List needs to be persisted across postbacks, so it also needs to be stored in the viewstate.
So I created a public property in the user control like so:
public List<int> ImageString {
get {
if (this.ViewState["ImageString"] != null) {
return (List<int>)(this.ViewState["ImageString"]);
}
return new List<int>();
}
set { this.ViewState["ImageString"] = value; }
}
And then I was hoping that from my aspx page I could add a line of code to add a value to the list like so:
this.LightBoxControl.ImageString.Add(value);
The problem I'm getting is that the the value is actually never added to the list. The count is always zero.
I'm sure its just that I've set the property up wrong, but I'm not sure how to right it..
Any help would be greatly appreciated.
Thanks
Al
Your getter is wrong. This is the correct variant:
get {
if (this.ViewState["ImageString"] == null) {
this.ViewState["ImageString"] = new List<int>();
}
return (List<int>)(this.ViewState["ImageString"]);
}
Here you first check whether there is something you need in ViewState already, and if there is no, you add it there. Then you return the item from ViewState - it is guaranteed to be there.
Your solution was bad because it did not place new List<int>() into the ViewState

Categories