In the following I've taken out irrelevant code. I've created a field called printString. The calculateButton_Click method does a heap of stuff, then I want to send it to a print-friendly page using response.write. However the printString variable doesn't seem to ever stop being "DEFAULT". DEFAULT is all that shows up on my blank page when I click the printButton_Click. Trimmed code below:
public partial class _Default : System.Web.UI.Page
{
private string _printString = "DEFAULT";
protected void Page_Load(object sender, EventArgs e)
{
Response.Buffer = true;
}
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
}
protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
}
When printButton is clicked it is using the value DEFAULT from when the variable is being set.
private string _printString = "DEFAULT";
Is your problem. You need to maintain the state of printString when the variable is modified. Simply assigning _printString to another value is not persisting the change. You could either write a function to assign _printString to the correct value when printButton is clicked, use ViewState or Session or assign _printString in the printButton click function directly as shown below.
protected void printButton_Click(object sender, EventArgs e)
{
_printString = "Harry Potter";
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
Will result in Harry Potter being wrote to the page.
To use Session:
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
Session["PrintString"] = _printString;
}
protected void printButton_Click(object sender, EventArgs e)
{
_printString = (string)Session["PrintString"];
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
ViewState:
ViewState["PrintString"] = "HarryPotter";
Then to retrieve the value you can simply do:
_printString = (string)ViewState["PrintString"];
http://msdn.microsoft.com/en-gb/library/ms972976.aspx
All (instance) variables are disposed at the end of the page's lifecycle since HTTP is stateless(even the controls). You could use a ViewState, HiddenField or Session variable instead.
private string PrintString
{
get
{
if (ViewState["PrintString "] == null || string.IsNullOrEmpty((String)ViewState["PrintString"]))
{
ViewState["PrintString"] = "DEFAULT";
}
return ViewState["PrintString"].ToString();
}
set { ViewState["PrintString"] = value; }
}
There are other options:
Nine Options for Managing Persistent User State in Your ASP.NET Application
The button click event is causing a postback and the _printString value is not being persisted. You need to store it in the calculate method via Session or Viewstate and then set it in the print for example: -
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
Session["bigstring"] = _printString;
}
protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
_printString = Session["bigstring"].ToString();
Response.Write(_printString);
Response.Flush();
Response.End();
}
Related
private void button1_Click(object sender, EventArgs e)
{
try
{
var WriteToFile = new System.IO.StreamWriter("student.txt"); //create textfile in default directory
WriteToFile.Write(txtStudNum.Text + ", " + txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
WriteToFile.Close();
this.Close();
}
catch (System.IO.DirectoryNotFoundException ex)
{
//add error message
}
}
private void button3_Click(object sender, EventArgs e)
{
File.AppendAllText("student.txt", "\r\n" + txtStudNum.Text + ", " +
txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
}
private void button4_Click(object sender, EventArgs e)
{
}
I want to calculate the average for txtModMark from the textfile once all the values have been entered. It will go under button 4 so when I click it, it calculates. I need to know how to skip the first few columns per row and get to the last column to perform the average calculation.
What's the point in reading from file then parse it and then convert to INT and then calculate average when you can do it directly using s List<int> like below:
declare a List<int> in your Form
List<int> marks = new List<int>();
Store the marks in button click event
private void button1_Click(object sender, EventArgs e)
{
try
{
var WriteToFile = new System.IO.StreamWriter("student.txt"); //create textfile in default directory
WriteToFile.Write(txtStudNum.Text + ", " + txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
WriteToFile.Close();
marks.Add(Convert.ToInt32(txtModMark.Text)); //add to list
}
catch (System.IO.DirectoryNotFoundException ex)
{
//add error message
}
}
In button4 click event calculate the average
private void button4_Click(object sender, EventArgs e)
{
int totalmarks = 0;
foreach(int m in marks)
totalmarks += m;
MessageBox.Show("Average Is: " + totalmarks / marks.Count);
}
I want to take the DateTime of the user's connection. I guess I will use the Session variable because I don't want that the DateTime changes at every refresh of my page.
Maybe something like that :
void Session_Start(object sender, EventArgs e)
{
Session["dateandhour"] = DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + "." + DateTime.Now.Hour + "." + DateTime.Now.Minute + "." + DateTime.Now.Second;
}
protected void Page_Load(object sender, EventArgs e)
{
string hour= (string)(Session["dateandhour"]);
lab10.Text = hour;
}
You can save the DateTime directly:
void Session_Start(object sender, EventArgs e)
{
Session["dateandhour"] = DateTime.Now;
}
protected void Page_Load(object sender, EventArgs e)
{
DateTime time = (DateTime)(Session["dateandhour"]);
lab10.Text = time.Hour;
}
This greatly simplifies subsequent use of the data.
I need help on this, I'm inserting file directory into the database but it does not take into account of the txtStoryTitle.Text in the database, for example, if I type HelloWorld in txtStoryTitle. It appears as Images/Story//(filename) instead of Images/Story/HelloWorld/(filename) in the DB. I am using MySQL (workbench).
please give me an advice/solutions on this, thanks in advance!
Here are the partial codes:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
EnsureDirectoriesExist();
String filepathImage = (#"Images/Story/" + txtStoryTitle.Text + "/" + e.FileName);
AjaxFileUpload1.SaveAs(Server.MapPath(filepathImage));
Session["filepathImage"] = filepathImage;
}
public void EnsureDirectoriesExist()
{
if (!System.IO.Directory.Exists(Server.MapPath(#"Images/Story/" + txtStoryTitle.Text + "/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath(#"Images/Story/" + txtStoryTitle.Text + "/"));
}
}
protected void btnDone_Click(object sender, EventArgs e)
{
if (Session["filepathImage"] != null)
{
string filepathImage = Session["filepathImage"] as string;
act.ActivityName = dropListActivity.SelectedItem.Text;
act.Title = txtStoryTitle.Text;
act.FileURL = filepathImage;
daoStory.Insert(act);
daoStory.Save();
}
As per your code.. the file path is "Images/Story/" + txtStoryTitle.Text + "/" + e.FileName"
and after providing txtStoryTitle.Text it saved as "Images/Story//FileName".. then it means txtStoryTitle.Text does'nt contain any text..
If its in .Net then make sure you set autopostback property of txtStoryTitle textbox to true.
and if it is already true then try to find out why this textbox does'nt resist its state.
I'm supposed to change the frmPersonnelVerified code behind to get the values from the Session state items.
Here is my session state code:
public partial class frmPersonnel : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
//Checking validation for the text boxes
if (string.IsNullOrEmpty((txtFirstName.Text ?? string.Empty).Trim()))
{
txtFirstName.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Please enter first name! <br />";
}
if (string.IsNullOrEmpty((txtLastName.Text ?? string.Empty).Trim()))
{
txtLastName.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Please enter last name! <br />";
}
if (string.IsNullOrEmpty((txtPayRate.Text ?? string.Empty).Trim()))
{
txtPayRate.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Please enter pay rate! <br />";
}
if (string.IsNullOrEmpty((txtStartDate.Text ?? string.Empty).Trim()))
{
txtStartDate.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Please enter start date! <br />";
}
if (string.IsNullOrEmpty((txtEndDate.Text ?? string.Empty).Trim()))
{
txtEndDate.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Please enter end date! <br />";
}
DateTime dt1;
DateTime dt2;
dt1 = DateTime.Parse(txtStartDate.Text);
dt2 = DateTime.Parse(txtEndDate.Text);
if (DateTime.Compare(dt1, dt2) > 0)
{
//Checking if the end date is greater than the start date
txtStartDate.BackColor = System.Drawing.Color.Yellow;
txtEndDate.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Start Date must not be greater than End Date! <br />";
}
else
{
//output information if correct validation
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
Server.Transfer("frmPersonalVerified.aspx");
}
}
catch (Exception ex)
{
}
}
}
I have a submit button that when pressed is supposed to input the above information into a text box on another page if it validates correctly. Right now it doesn't do that.
Here is my code on frmPersonnalVerified:
public partial class frmPersonnelVerified : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Inputs information from frmPersonnel and places it into the
//textbox called "txtVerifiedInfo"
txtVerifiedInfo.Text = Request["txtFirstName"] +
"\n" + Request["txtLastName"] +
"\n" + Request["txtPayRate"] +
"\n" + Request["txtStartDate"] +
"\n" + Request["txtEndDate"];
}
}
You're storing the variables in Session but then trying to access them through the Request object. Change it to Session, and it should work:
public partial class frmPersonnelVerified : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Inputs information from frmPersonnel and places it into the
//textbox called "txtVerifiedInfo"
txtVerifiedInfo.Text = Session["txtFirstName"] +
"\n" + Session["txtLastName"] +
"\n" + Session["txtPayRate"] +
"\n" + Session["txtStartDate"] +
"\n" + Session["txtEndDate"];
}
}
However, putting values into Session can be problematic so be cautious.
This is the order in which the events are being handled:
Page_Load
btnSubmit_Click
Page_Render
If you move your code from Page_Load to Page_Render it should work.
protected void Page_Render(object sender, EventArgs e)
{
//Inputs information from frmPersonnel and places it into the
//textbox called "txtVerifiedInfo"
txtVerifiedInfo.Text = Request["txtFirstName"] +
"\n" + Request["txtLastName"] +
"\n" + Request["txtPayRate"] +
"\n" + Request["txtStartDate"] +
"\n" + Request["txtEndDate"];
}
In your verified class you're trying to get the values from the request object not the session object.
The Request object will give you accesss to information either posted back (E.g. form fields) or part of the query string and as the name suggest is associated with a specific request. The Session object is associated with the current user session and you can place and retrieve arbitrary objects in that object.
As a side note since this does not seem to have anything to do with your problem.
It's seldom needed to access the Request object in ASP.NET for values relying on ASP.NETs capabilities to construct object graphs based on request data is generally a better solution.
in code this could look like:
public partial class frmPersonnelVerified : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Inputs information from frmPersonnel and places it into the
//textbox called "txtVerifiedInfo"
txtVerifiedInfo.Text = Session["txtFirstName"] +
"\n" + Session["txtLastName"] +
"\n" + Session["txtPayRate"] +
"\n" + Session["txtStartDate"] +
"\n" + Session["txtEndDate"];
}
}
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;
}
}