Problems with textboxes and page load in C# - c#

Okay here I have some code from my project at the moment.
Basically the user goes onto the page and their current password is in the password textbox, and their avatar is selected in the droplist.
They can change their password by editing the text in the textbox and change their avatar by selecting a new one from the list. This is then written to the file where this information is kept. It writes to the file okay, but it writes what was initially in the textbox and droplist.
If i comment out these lines in the page load:
avatarDropList.SelectedValue = Session["avatar"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
It updates the file properly, but this is not what I want as I want the old password displayed there initially as well as the avatar to be selected in the dropbox.
Code below:
public partial class TuitterProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
avatarImage.ImageUrl = "~/images/avatars/" + Session["avatar"] + ".gif";
avatarDropList.SelectedValue = Session["avatar"].ToString();
userNameTextbox.Text = Session["user"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
}
protected void okButton_Click(object sender, ImageClickEventArgs e)
{
string username = Session["user"].ToString();
string password = Session["password"].ToString();
string newPassword = newPasswordTextbox.Text;
string newAvatar = avatarDropList.SelectedValue;
int allDataReference = -1;
//Each element in the array is a string(Username Password Avatar)
string[] allData = File.ReadAllLines(Server.MapPath("~") + "/App_Data/tuitterUsers.txt");
for (int i = 0; i < allData.Length; i++)
{
string[] user = allData[i].Split(' ');
if (user[0] == username && user[1] == password)
{
allDataReference = i;
}
}
if (allDataReference > -1)
{
Session["avatar"] = newAvatar;
Session["password"] = newPassword;
allData[allDataReference] = username + " " + newPassword + " " + newAvatar;
File.WriteAllLines(Server.MapPath("~") + "/App_Data/tuitterUsers3.txt", allData);
}
}
}

In the ASP.Net page event lifecycle, Page_Load is called on every request. What you are doing here is resetting the value of the TextBox every time the page loads, which will include the time that you press the button to save the profile.
All you need to do is check for the current request being a postback when you set your initial values:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
avatarImage.ImageUrl = "~/images/avatars/" + Session["avatar"] + ".gif";
avatarDropList.SelectedValue = Session["avatar"].ToString();
userNameTextbox.Text = Session["user"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
}
}

Related

Passing variables to another Webpage

I'm trying to get variables from textboxes in one page, then pass them to be displayed in another page. Seems like I should use sessions (since that was the topic this assignment is for). The commented-out code is various methods I've tried that have not worked.
On the start page:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
}
//This is a button link that sends to the next page, "Results"
protected void cbtnlSubmit_Click(object sender, EventArgs e)
{
string sName = "";
int sSize = 0;
string sTopping = "";
decimal sPrice = 0M;
if (IsPostBack)
{
Validate();
if (IsValid)
{
sName = ctbName.Text;
sSize = Convert.ToInt32(ctbSize.Text);
sTopping = ctbTopping.Text;
sPrice = Convert.ToDecimal(ctbPrice.Text);
if (string.IsNullOrEmpty(sTopping) == true)
{
sTopping = "cheese";
}
/* DOESN'T WORK
Session.Add(sName, sSize);
Session.Add(sTopping, sPrice);
Server.Transfer("Results.aspx");
*/
/*DOESN'T WORK
Session["pizza"] = new Pizza()
{
name = sName,
size = sSize,
topping = sTopping,
price = sPrice
};
*/
//ALSO DOESN'T WORK
Session["name"] = sName;
Session["size"] = sSize;
Session["topping"] = sTopping;
Session["price"] = sPrice;
Response.Redirect("Results.aspx");
}
}
}
}
This is the "Results" page that should display the variables
public partial class Results : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count != 0)
{
lblName.Text = Session["name"].ToString();
string size = Session["size"].ToString();
string topping = Session["topping"].ToString();
string price = Session["price"].ToString();
string pizzaInfo = (size + " inch pizza with " + topping + " for $" + price.ToString());
lblPizzaInfo.Text = pizzaInfo;
/*
string name = Session.Keys[0];
int size = Convert.ToInt32(Session[name]);
string topping = Session.Keys[1];
decimal price = Convert.ToDecimal(Session[topping]);
string pizzaInfo = (size.ToString() + " inch pizza with " + topping + " for $" + price.ToString());
lblName.Text = name;
lblPizzaInfo.Text = pizzaInfo;
*/
}
lblName.Text = "Meaghan";
}
}
Both pages display. The lblName.Text set at the end of the secondary page is a test to make sure the labels are visible (they are), but no information is being passed to the secondary page. That label only displays if I put it outside the if statement; nothing inside the if statement executes. I have tried reading the recommended questions and discovered I should enable "sessionState", which I did for both pages, but the program still doesn't work.
I selected EnableSessionState as True in the properties and it says EnableSessionState = "True" at the top of the aspx files. I added to the web.config file. So I guess the session state mode is "InProc" mode?
I tried adding the Session["test"] = "Hello" into the Default page and Response.Write(Session["test"]) into the Results page. Now it throws a NullReferenceException at lblName.Text = Session["name"].ToString() [inside the if statement].
You need the following in your Web.config at the root of your project:
<sessionState mode="InProc" cookieless="false" timeout="10" />
Can you please confirm or not if you have this entry in your config file ?
It should be located under
<configuratio>
<system.Web>
Further information on sessionState: https://msdn.microsoft.com/en-us/library/h6bb9cz9(v=vs.71).aspx

How can I update image in listview in gridview format?

how can i update image in listview in gridview formate using folder path in asp.net in c#?
protected void UpdateButton_Click(object sender, EventArgs e)
{
TextBox ApplicantIdTextBox = (TextBox)RadListView8.FindControl("ApplicantIdTextBox");
FileUpload photoTextBox = (FileUpload)RadListView8.FindControl("photoTextBox");
string fileName1 = Path.GetExtension(ApplicantIdTextBox + photoTextBox.FileName);
string fileSavePath = Server.MapPath("ImageStorage/" + fileName1);
tblPersonalInfo pi = new tblPersonalInfo();
pi.photo = fileName1;
photoTextBox.SaveAs(fileSavePath);
dbcontext.AddTotblPersonalInfoes(pi);
dbcontext.SaveChanges();
}
But it show me error...What can i do?
Server Error in '/HrPayRoll' Application.
Object reference not set to an instance of an object.
I'd rewrite it something like this and then run it in debug mode and see what line the error is on. You were trying to use applicantIdTextBox as a string, although I would have thought that would give a different error:
protected void UpdateButton_Click(object sender, EventArgs e)
{
TextBox applicantIdTextBox = RadListView8.FindControl("ApplicantIdTextBox") as TextBox;
FileUpload photoTextBox = RadListView8.FindControl("photoTextBox") as FileUpload;
if ((applicantIdTextBox != null) && (photoTextBox != null))
{
string fileName = Path.GetExtension(applicantIdTextBox.Text + photoTextBox.FileName);
string fileSavePath = Server.MapPath("ImageStorage/" + fileName);
tblPersonalInfo personalInfo = new tblPersonalInfo();
personalInfo.photo = fileName;
photoTextBox.SaveAs(fileSavePath);
dbcontext.AddTotblPersonalInfoes(personalInfo);
dbcontext.SaveChanges();
}
}

Update a users profile information using simple textboxs

So I have made a log in system and now I wan't to allow the users to update their information. I thought that this code would work but it did not, here it is:
public partial class Account_Update : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MembershipUser usr = Membership.GetUser();
if (usr.IsApproved == false)
{
Response.Redirect("~/Login.aspx");
}
var p = Profile.GetProfile(usr.UserName);
/* Displays all current profile information once the page loads */
FirstName.Text = p.fName;
LastName.Text = p.lName;
Address.Text = p.Address;
Email.Text = usr.Email;
Company.Text = p.Company;
}
/* Simple button to take you to the home screen */
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("~/default.aspx");
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
MembershipUser usr = Membership.GetUser();
var p = Profile.GetProfile(usr.UserName);
/* Update all information that the user has changed */
p.fName = FirstName.Text;
p.Save();
p.lName = LastName.Text;
p.Save();
p.Address = Address.Text;
p.Save();
usr.Email = Email.Text;
Membership.UpdateUser(usr);
p.Company = Company.Text;
p.Save();
Success.Text = "User Information has been updated";
/* Redisplaying the updated user information */
FirstName.Text = p.fName;
LastName.Text = p.lName;
Address.Text = p.Address;
Email.Text = usr.Email;
Company.Text = p.Company;
}
}
The problem seems to be that whatever I change the text to in the text-box is not changing from what was originally in the text-box. So if initially the users first name was Bob and I change it to Robert when I hit the update button it does not change it to Robert. this seems like a simple fix but I'm sort of lost. So to summarize the main question is how do I update the users information to the new text that the user enters in the textbox.
put !Ispostback at the page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MembershipUser usr = Membership.GetUser();
if (usr.IsApproved == false)
{
Response.Redirect("~/Login.aspx");
}
var p = Profile.GetProfile(usr.UserName);
/* Displays all current profile information once the page loads */
FirstName.Text = p.fName;
LastName.Text = p.lName;
Address.Text = p.Address;
Email.Text = usr.Email;
Company.Text = p.Company;
}
}
If you don't use it, alwyas when the info going to the server you will get the olds value.
cheers.

Rendering server control in a callback

I have a bunch of different panels that are custom server controls, which inherits CompositeControl. The panels are rendered by using the CreateChildControls(). I have a page where I am displaying them based off of a users selection from a comboBox. When you change the selection it does a callback for a callback panel (DevExpress control), which is like an update panel. Based on the selection it adds the panel to the callback panel. But it seems that if you do this from a callback the server controls life cycle doesn't get started, so it never calls CreateChildControls() or OnPreRender(). Any ideas on how to make this work? EnsureChildControls() doesn't seem to helping.
Here is some example code of one of the panels
protected override void CreateChildControls()
{
base.CreateChildControls();
String strParentID = this.ClientInstanceName.Length > 0 ? this.ClientInstanceName : this.ClientID;
String strID = "";//Used as ID and ClientInstanceName.
String strKey = "";//Used in the ID and as the ControlInfo key.
if (!DesignMode)
{
//*******************************************************************
ASPxLabel lblUnit = new ASPxLabel();
lblUnit.Text = "Select Unit(s)";
callbackEdit.Controls.Add(lblUnit);
//*******************************************************************
strKey = "btnUnitSelector";
strID = strParentID + "_" + strKey;
btnUnitSelector = new ASPxButton()
{
ID = strID,
ClientInstanceName = strID,
CssFilePath = this.CssFilePath,
CssPostfix = this.CssPostfix,
SpriteCssFilePath = this.SpriteCssFilePath,
};
btnUnitSelector.Width = Unit.Pixel(180);
btnUnitSelector.AutoPostBack = false;
this.listControlInfo.Add(new ControlInfo(strKey, btnUnitSelector.ClientInstanceName, btnUnitSelector.ClientID));
callbackEdit.Controls.Add(btnUnitSelector);
//*******************************************************************
strKey = "unitPopup";
strID = strParentID + "_" + strKey;
unitPopup = new UnitPopup.UnitPopup();
unitPopup.ID = strID;
unitPopup.ClientInstanceName = strID;
unitPopup.btnOk_AutoPostBack = false;
unitPopup.ShowOnlyUnits = false;
unitPopup.DataSource = GlobalProperties.Company_UnitsAndAreas;
unitPopup.DataBind();
btnUnitSelector.ClientSideEvents.Click = "function (s, e) { " + unitPopup.ClientInstanceName + ".Show(); }";
unitPopup.ClientSideEvents.MemberSet = "function (s, e) { " + btnUnitSelector.ClientInstanceName + ".SetText(" + unitPopup.ClientInstanceName + ".selectedMemberName); }";
Controls.Add(unitPopup);
//*******************************************************************
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ClientScriptManager cs = this.Page.ClientScript;
//Register an embedded JavaScript file. The JavaScript file needs to have a build action of "Embedded Resource".
String resourceName = "QSR_ServerControls.Controls.DashboardControls.SalesChart.SalesChart.js";
cs.RegisterClientScriptResource(typeof(SalesChart), resourceName);
}
Here is some sample code of adding a panel
private void PopulatePanel(string panel)
{
tblDescCell.Controls.Add(new LiteralControl(GetPanels().Select("[PanelName] = '" + panel + "'")[0]["PanelDescription"].ToString()));
if (panel == "SalesChart")
tblTopLeftCell.Controls.Add(new SalesChart.SalesChart());
}
void callbackMain_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
PopulatePanel(e.Parameter);
}
During callback requests PreRender and Render methods are not executed (this is the main difference from PostBack request). But CreateChildControls should be executed. Please provide more information or code example.

Value stored in a variable in an event handler is null later on, why?

In my code I write the value from DropDownList1.SelectedItem.Text to Label1.Text and into uploadFolder in the DropDownList1_SelectedIndexChanged method. When the ASPxUploadControl1_FileUploadComplete method is called, the value is in Label1.Text but not in uploadFolder, which is null. Why is this?
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem != null)
{
Label1.Text = "You selected " + DropDownList1.SelectedItem.Text;
uploadFolder = DropDownList1.SelectedItem.Text;
}
}
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
string uploadDirectory = Server.MapPath("~/files/");
//string uploadDirectory = #"\\DOCSD9F1\TECHDOCS\";
string fileName = e.UploadedFile.FileName;
string path = (uploadDirectory + uploadFolder + "/" + fileName);
//string path = Path.Combine(Path.Combine(uploadDirectory, uploadFolder), fileName);
e.UploadedFile.SaveAs(path);
e.CallbackData = fileName;
}
}
It looks like uploadFolder is a variable you've declared on your page, something like this:
public class MyPage : System.Web.UI.Page
{
string uploadFile = null;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// Your code here
}
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
// Your code here
}
}
What's happening is that the content of uploadFile that you're setting in DropDownList1_SelectedIndexChanged isn't being preserved between post-backs, because it isn't a property of one of the controls on the page. You need to store the value somewhere that gets persisted, such as the View State or in Session State.
To do this, you should add to the DropDownList1_SelectedIndexChanged method so it reads something like:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem != null)
{
Label1.Text = "You selected " + DropDownList1.SelectedItem.Text;
Session["UploadFolder] = DropoDownList1.SelectedItem.Text;
}
}
And adjust the ASPxUploadControl1_FileUploadComplete method so it extracts `uploadFolder from the Session:
string path = (uploadDirectory + Session["UploadFolder"] + "/" + fileName);
If you want to make it look more elegant than that, consider using ViewState in this sort of way:
public string UploadFolder
{
get
{
return (string)ViewState["UploadFolder"];
}
set
{
ViewState["UploadFolder"] = value;
}
}
You can then do this:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem != null)
{
Label1.Text = "You selected " + DropDownList1.SelectedItem.Text;
UploadFolder = DropoDownList1.SelectedItem.Text;
}
}
And:
string path = (uploadDirectory + UploadFolder + "/" + fileName);
I would imagine that you are not persisting uploadFolder through page post backs. Store the value in a hidden field, e.g.:
<asp:HiddenField ID="hidden_UploadFolder" runat="server" />
And then:
hidden_UploadFolder.Value = DropDownList1.SelectedItem.Text;
You can then read it again on the next post back:
string uploadFolder = hidden_UploadFolder.Value;
Make sure you add error trapping.
It looks like you are setting the value for upload folder in one postback and using it in another. If you want to persist data between postbacks use the Session.
ex.
Session["uploadFolder"] = DropDownList1.SelectedItem.Text;
string path = (uploadDirectory + Session["uploadFolder"].ToString() + "/" + fileName);
Try
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem != null)
{
Label1.Text = "You selected " + DropDownList1.SelectedItem.Text;
Session["uploadFolder"] = DropDownList1.SelectedItem.Text;
}
}
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
string uploadDirectory = Server.MapPath("~/files/");
//string uploadDirectory = #"\\DOCSD9F1\TECHDOCS\";
string fileName = e.UploadedFile.FileName;
string uploadfolder = Session["uploadFolder"] as String;
string path = (uploadDirectory + uploadfolder + "/" + fileName);
//string path = Path.Combine(Path.Combine(uploadDirectory, uploadFolder), fileName);
e.UploadedFile.SaveAs(path);
e.CallbackData = fileName;
}
}

Categories