Asp.net property value set to zero on button click - asp.net

On my ASP.net page I am assigning a session variable to a private property on Page_Load
private int userid{ get; set;}
if (!IsPostBack)
{
if (Session["userid"] != null)
{
userid= int.Parse(Session["userid"].ToString());
}
}
And in my Add button click event I am using userid
protected void btnAdd_Click(object sender, EventArgs e)
{
doSomething(userid);
}
Initially the value is retrieved and stored in userid property but in btnAdd_Click, the userid becomes 0. I moved the code out of if(!IsPostBack) block, that fixed the problem but left me wondering what set my userid property to zero once it is already set on page load. Not clear whether on button click a new instance of the page is returned or what? Any guidance?

You could just remove the stuff from the page load, since the data is in the session, and just change the property to the following:
private int userid{ get{ return int.Parse(Session["userid"].ToString()); } }

Related

.net using and reaching public value

I wrote this code in .NET. When I want to change ‘s’ by clicking button2, it doesn’t change. I mean after clicking button2 and then I click Button1 to see the changes but nothing changes. How can I change and access the value of ‘s’ properly. What am I doing wrong?
public string s;
public void Button1_Click(object sender, EventArgs e)
{
Label1.Text = s;
}
public void Button2_Click(object sender, EventArgs e)
{
s = TextBox1.Text;
}
You need to understand how web applications work.
In each post back an instance of the class that handles the page is loaded, so when you click on button 1, the page does a post back and loads again, so this way the variable s isn't loaded with your content.
To make this code work, you need to save the S values on the page viewstate.
try replacing "public string s;" with this:
public string s
{
get { return (string)ViewState["myValue"]; }
set [ ViewState["myValue"] = value };
}
More Information about Page Life Cycle at: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

Store and transfer values in a ascx control

I have a problem that I have been struggling with for some time, and it is regarding transfering values from one control to another.
Basically I have two .ascx controls. On control1: I have an email textbox called txtEmail. The txtEmail is used to save the email in the SQL table, and on update button click, I load Control2 that has a email textbox as well. I need the emailtext box from control1 to be available on email textbox on control2.
I have tried all kinds of different ways but to no avail. I even tried using delegates and events but I can't make it work.
Does anyone know how I can do this.
Regards
Please find below the code:
public event EventHandler Notify;
public string Email
{
get { return txtEmail.Text; }
set {Email= value ; }
}
//button that will handle the update
protected void btnUpdateDB_Click(object sender, EventArgs e)
{
var email = txtEmail.Text.ToString();
public BaseClass.BAL.MBAL m = new BaseClass.BAL.MBAL();
var s = new BaseClass.Controllers.m();
s.email=email;
if(m.save(s)!=0) txtMsave.Text="Saved....";
}
//second control
public void notifyEmailChange(object sender,EventArgs e)
{
txtUsername.Text = member1.Email;
}
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
member1.Notify += new EventHandler(notifyEmailChange);
}
}
public string email {
set { txtUsers.Text = value; }}
Maybe I am trivializing the problem, but if you are wanting to be able to read/write to the text box on each of the custom controls, just make a public property that reads and writes to the textbox on each of the two controls.
public string EmailAddress {
get {
return txtEmailAddress.Text;
}
set {
txtEmailAddress.Text = value;
}
}
Now the page that contains the two controls can read the email address from the first control and write it into the email address text box in the second control.
If I am misunderstanding the problem, let me know.
The way that I have done this in the past is to have
UserControl1 have a custom event called (for instance) Notify.
The containing control wires Notify to an EventHandler
When notify fires (on the update) the consuming event handler fires and this event handler updates the email on UserControl2
Might seem overengineered but because UserControl2 can't "see" UserControl1 I think this is the way to go
Example
In UserControl1
public event EventHandler Notify;
and within the update button click event handler
if(Notify != null)
{
Notify(this, new EventArgs());
}
In parent control
in Page_Load
ucUserControl2.Notify += new EventHandler(NotifyUserControl);
and to set the message
protected void NotifyUserControl(object sender, EventArgs args)
{
ucUserControl2.Email = ucUserControl1.Email;
}
You obviously need public properties in UserControls to expose the Email text

how to insert data within a calendar cell into a database

i have a calender and i was able to add text-box inside the cell using the day-render event but what i am trying to do is allow the user to add data to the text-box and then press add and the content is added to a database and showed inside that same text-box:
here is what i did:
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.SelectedDate = DateTime.Now;
}
protected void update(object sender, DayRenderEventArgs e)
{
TextBox tb = new TextBox();
Button1.click += new EventHandler(insert);
e.Cell.Controls.Add(Button1);
e.Cell.Controls.Add(textBox2);
}
protected void insert(object sender, EventArgs e)
{
}
and i know how to insert the data but i am lost on how to identify it and output it back to the same text box
thanks
Well I'm not sure exactly what part you are lost on based on your question, so short of providing a complete working example I'll hit some of the main points:
1) To identify the data you are inserting, attach a date (and time if applicable) to the record. (Edit: are you looking for a mechanism to accomplish this? If so post your current DayRender handler code and Calendar markup).
2) To populate individual day data in a calendar, use Calendar.VisibleDate (to filter DB results) in a Page.Load handler to load a data structure (such as a List<T>) with day data for the entire month. Then in a Calendar.DayRender handler, add appropriate records from the structure to the e.Cell.
3) To cause the new results to show up on the first page refresh after insertion, you should be able to get away with using a Response.Redirect to the current page after insertion. This will cause the page generation process to restart, but you will lose ViewState.
Edit: Here is a basic prototype of what I tried to describe above. Note that you could pre-fetch into any enumerable data type, I use a List<T> here.
//Page code-behind
public partial class Default2 : System.Web.UI.Page
{
List<DataObject> liCurrentMonth = new List<DataObject>();
protected void Page_Load(object sender, EventArgs e)
{
liCurrentMonth = DataObject.GetCurrentMonth(Calendar1.VisibleDate);
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
foreach (DataObject item in liCurrentMonth)
{
if (item.date == e.Day.Date)
{
Literal lit = new Literal();
lit.Text = item.text;
e.Cell.Controls.Add(lit);
}
}
}
}
//Data layer object
public class DataObject
{
public DateTime date { get; set; }
public string text { get; set; }
public static List<DataObject> GetCurrentMonth(DateTime currentdate)
{
//Get items from the db here, based on currentdate parameter
//and populate the List<DataObject>.
return new List<DataObject>();
}
}
I'm not sure you'll get this to work. Its the page viewstate that remembers the value entered into textboxes etc. Viewstate is created just before the page renders. The Calendar DayRender event is called during the calendars rendering, and hence after viewstate has done its thing. Therefore the viewstate mechanism is not aware of the existance of the textboxes and so will not track their content.
Perhaps you could assign each textbox an ID based on the month and day number, on postback you could check for this control ID in the Request.Form collection and do something with the data?

How to change property of UserControl on PostBack?

Let's say I have a page with my custom UserControl (containing only asp:Literal and some string property) and a button. Now I want to change Literal's text on button click, so I change my control's string property in button clicked event. Like this:
//in aspx
protected void Button1_Click(object sender, EventArgs e)
{
testControl.Text = "triggered";
}
The problem is my Literal remains unchanged because Page_Load event fires first and creates my custom control, then Button_Clicked fires and changes property but as control is already created, it does nothing. This is my control's code behind:
public partial class TestControl : System.Web.UI.UserControl
{
public string Text { get; set; } }
protected void Page_Load(object sender, EventArgs e)
{
lblTest.Text = Text;
}
}
I figured out that if I move any logic in custom control from Page_Load to property setter it will change like intended. Like this:
public string Text { get { return lblTest.Text; } set { lblTest.Text = value; } }
Is there any other (better) way to do this? My real problem involves much more complicated controls than described here, but problems remains the same: on any postback all properties set in event handlers are ignored.
Moving all logic from Page_Load to Page_PreRender solved the problem. Now properties are set before logic executes. I'll wait for other answers to check if there is better solution and if there are any drawbacks of using Page_PreRender.
This video might help: How Do I: Persist the State of a User Control During a Postback

Why is my DropDownList empty on Postback?

I've looked at answers to some similar question but I still can't seem to figure this out. I think I'm misunderstanding something about how ASP.NET works.
In the standard ASP.Net 4.0 'Create a new Account' form, I've added a DropDownList containing Roles to be selected for the new account. in the aspx page, the control looks like this:
<asp:DropDownList ID="RoleList" Width="100px" runat="server"></asp:DropDownList>
I am then populating the List in the Page_Load Event:
protected void Page_Load(object sender, EventArgs e)
{
RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
if (Page.IsPostBack)
{
return;
}
//Set the Role List Selections
DropDownList roleList = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("RoleList");
//set the role list
String[] roles = Roles.GetAllRoles();
foreach (String role in roles)
{
roleList.Items.Add(new ListItem(role, role));
}
}
I can see/select a role from the generated html. The problem arises when the 'Submit' button for creating a User is clicked:
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);
string continueUrl = RegisterUser.ContinueDestinationPageUrl;
if (String.IsNullOrEmpty(continueUrl))
{
continueUrl = "~/";
}
//set user role
DropDownList roleList = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("RoleList");
Roles.AddUserToRole(RegisterUser.UserName, roleList.SelectedValue);
Response.Redirect(continueUrl);
}
Here, The roleList object contains zero items, and has no selected values. Somehow, I am losing the populating items between selection of the item, and the submit. Any idea what I'm doing wrong?
Put your dropdownlist loading into the OnInit function instead - then it should be loaded properly when RegisterUser_CreatedUser is called:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//Set the Role List Selections
DropDownList roleList = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("RoleList");
//set the role list
String[] roles = Roles.GetAllRoles();
foreach (String role in roles)
{
roleList.Items.Add(new ListItem(role, role));
}
}
I had a similar issue that change of radio button selection would auto postback the page and the dropdown list items would disappear after the page is back.
Solution
Check IIS -> Your WebSite -> Pages & Controls -> Enable Viewstate & Enable Sessionstate should be set to true.
Hope this helps.
The code below bypasses the proper databinding on the page load.
if (Page.IsPostBack)
{
return;
}
You need to bind this control each time so that the values are present when click events are called. You may also get event errors for operating on selected items that are no longer present.
Did you try embracing your binding with the following condition?
if (!Page.IsPostBack)
{
//Binding goes here
}

Resources