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"];
}
}
Related
This is the webform1 code and I made a string called pass to store the text in. What should I do in webform2 to display the message based on the conditions?
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("two.aspx", true);
if (Request.Form["TextBox1"] != null && Request.Form["TextBox2"] != null)
{
if (RadioButton2.Checked)
{
//pass = Response.ToString().Insert(Response.ToString().Count(), " " + "Welcome, " + Server.HtmlEncode(Request.QueryString["TextBox1"]) + ". <br/> The url is " + Server.HtmlEncode(Request.Url.ToString()));
pass = "Thank you Ms. " + TextBox1.Text + "Your Registration has been successfully completed" ;
}
else if (RadioButton1.Checked)
{
pass = "Thank you Mr. " + TextBox1.Text + "Your Registration has been successfully completed";
}
}
}
Based on whatever i understand, i am providing some solution:
in webform1.aspx:->place below code last line before closing the function
Application["pass_value"] = pass;
Response.Redirect("~/webform2");
Response.Redirect("two.aspx", true);->Not required
in webform2.aspx:
Label1.Text = Application["pass_value"].ToString();
in webform2.aspx.cs design page:
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
I am making a windows form application that takes various game entries (title,genre,price) and then stores them in an array with a maximum of four entries.
The error I am having is that if there are no values entered in my text boxes, I want a message box to appear to force the user to enter values. This happens.
The problem is that after this, it does not give the user another try. It just stops the program. I have tried using a try catch statement to do this but I am not quite sure how to use this. Would this be the correct solution?
namespace gameForm
{
public partial class gameEntryForm : Form
{
public gameEntryForm()
{
InitializeComponent();
}
struct Game
{
public string Title;
public string Genre;
public decimal Price;
}
static Game[] aNewGame = new Game[4]; //max size of the array is 4
static int newGameEntryIndex = 1;
private void gameEntryForm_Load(object sender, EventArgs e)
{
aNewGame[0].Title = "golf tour"; //this is a game already stored in the database
aNewGame[0].Genre = "sports";
aNewGame[0].Price = 1.99m;
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
}
if (String.IsNullOrEmpty(tbTitle.Text))
{
MessageBox.Show("please enter a Game title");
}
if (String.IsNullOrEmpty(tbPrice.Text))
{
MessageBox.Show("please enter a Game price");
}
}
//catch()
//{
//}
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
aNewGame[newGameEntryIndex].Genre = tbGenre.Text;
aNewGame[newGameEntryIndex].Price = Convert.ToDecimal(tbPrice.Text);
newGameEntryIndex++;
MessageBox.Show("entry saved");
//clears the text boxes
tbTitle.Clear();
tbGenre.Clear();
tbPrice.Clear();
}
private void btnShow_Click(object sender, EventArgs e)
{
rtbShow.Text = "Game Details \n\nGame 1 \n" + aNewGame[0].Title + "\n" + aNewGame[0].Genre + "\n" + aNewGame[0].Price + "\n\n" + "Game 2 \n" + aNewGame[1].Title + "\n" + aNewGame[1].Genre + "\n" + aNewGame[1].Price + "\n\n" + "Game 3 \n" + aNewGame[2].Title + "\n" + aNewGame[2].Genre + "\n" + aNewGame[2].Price + "\n\n" + "Game 4 \n" + aNewGame[3].Title + "\n" + aNewGame[3].Genre + "\n" + aNewGame[3].Price; ;
}
//clears the rich text box
private void btnClear_Click(object sender, EventArgs e)
{
rtbShow.Clear();
}
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Add a return, no try/catch required:
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
return; // Exit current function
}
Try/catch is for when you have exceptions.
Try-Catch is of no use to you.
What you should do is in the btnSave_Click method return when the textboxes are not populated:
if (String.IsNullOrWhiteSpace(tbGenre.Text) ||
String.IsNullOrWhiteSpace(tbTitle.Text) ||
String.IsNullOrWhiteSpace(tbPrice.Text)
{
MessageBox.Show("Please enter a game genre, game title and game price.");
return;
}
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
...
There is another solution you could do. Only activate the Save-button if all three textboxes has values in them.
Something like:
private void ValidateGameData(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(tbGenre.Text) ||
String.IsNullOrWhiteSpace(tbTitle.Text) ||
String.IsNullOrWhiteSpace(tbPrice.Text))
{
btnSave.Enabled = false;
}
else
{
btnSave.Enabled = true;
}
}
tbGenre.TextChanged += ValidateGameData;
tbTitle.TextChanged += ValidateGameData;
tbPrice.TextChanged += ValidateGameData;
In your code for btnSave_Click you are testing the value of the various TextBoxes and displaying a message if they are NULL or empty.
However, you continue execution of your code even if they are NULL or empty.
You should stop processing more code if the conditions fail so that you don't try to use the NULL\empty values.
Something like:
private void btnSave_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
}
else if (String.IsNullOrEmpty(tbTitle.Text))
{
MessageBox.Show("please enter a Game title");
}
else if (String.IsNullOrEmpty(tbPrice.Text))
{
MessageBox.Show("please enter a Game price");
}
else
{
// You forgot to create the new game at this index
aNewGame[newGameEntryIndex] = new Game();
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
aNewGame[newGameEntryIndex].Genre = tbGenre.Text;
aNewGame[newGameEntryIndex].Price = Convert.ToDecimal(tbPrice.Text);
newGameEntryIndex++;
MessageBox.Show("entry saved");
//clears the text boxes
tbTitle.Clear();
tbGenre.Clear();
tbPrice.Clear();
}
}
I've also added a line:
aNewGame[newGameEntryIndex] = new Game();
As I couldn't see anywhere that you created the new Game object before trying to set it's properties.
I need some guidance here on why this isn't working:
So here's the issue, I want to give my users a little status field so they can check how long it will take and get a coffee or two for them.
My Problem is that the statusfield (2 Labels), are not updated during the process.
This is my current code :
private void Cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void start_change_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Start process?", "DateChanger", MessageBoxButtons.OKCancel, MessageBoxIcon.Hand);
if (dr == DialogResult.OK)
{
//get files
List<String> d = new List<String>();
label_status_title.Text = "Status: collecting Data, take a coffee while waiting.\nfiles changed: 0 files";
d = getFiles("H:\\");
int i = 0;
double diff = 0.0;
//modify files
label_status_title.Text = "Status: changing files.\nfiles changed: 0/" + d.Count + " files.";
foreach (String s in d)
{
String label = "\nfile: " + s;
//create newDate and modify creation and lastwrite
DateTime actualDate = Directory.GetLastWriteTime(s).Date;
DateTime newDate = new DateTime(2015, 03, 01);
diff = (newDate - actualDate).TotalDays;
label += "\nactual creation date: " + Directory.GetCreationTime(s).Date;
label += "\nnew creation date: " + newDate.Date;
label += "\nactual last write date: " + Directory.GetLastWriteTime(s).Date;
label += "\nnew last write date: " + newDate.Date;
if (diff > 400)
{
try
{
//set new timevalues
Directory.SetCreationTime(s, newDate);
Directory.SetCreationTimeUtc(s, newDate);
Directory.SetLastWriteTime(s, newDate);
Directory.SetLastWriteTimeUtc(s, newDate);
}
catch (UnauthorizedAccessException UAE)
{
}
i++;
label += "\nchange needed.";
}
else
{
label += "\nchange not needed.";
}
label_status.Text = label;
label_status_title.Text = "Status: changing files.\nfiles changed: " + i + "/" + d.Count + " files.";
}
MessageBox.Show("Process finished, changed: " + i + "/" + d.Count + " files.");
}
}
private List<String> getFiles(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(getFiles(d));
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
return files;
}
private void DateChanger_Load(object sender, EventArgs e)
{
String label = "";
label_status_title.Text = "Status: \nfiles changed: 0 files";
label += "file: ";
label += "\nactual creation date: ";
label += "\nnew creation date: ";
label += "\nactual last write date: ";
label += "\nnew crealast writetion date: ";
label_status.Text = label;
}
I also tried the suggestion of using MethodInvoker, but that also didn't work either. Any guidance or suggestions here are appreciated.
Thanks.
Mirko
p.s. if there is a better solution than using labels or text boxes for this feel free to tell me. :)
Youre Method start_change_Click(object sender, EventArgs e) is blocking the main thread. To avoid this, use a separate thread to update the labels.
Check out this post: Thread freezes main UI
Just refresh the Label after assigning it a new Text value.
label_status_title.Text = "Status: changing files.\nfiles changed: " + i + "/" + d.Count + " files.";
label_status_title.Refresh(); //added
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();
}
I have these codes for uploading csv file. Also, I have put a GridView to display its contents. Now, what I want to do is to display error lines from the GridView, for example, if there are missing words in a particular column or row, I would want to display that that particular line is empty, and that the user has to reupload with that particular line updated. The thing is, I'm really new with this, I hope someone could help me! I do not know how to retrieve the error lines and display it on the website. These are my codes :
protected void btnUpload_Click(object sender, EventArgs e)
{
string strFileNameOnServer = fileUpload.PostedFile.FileName;
string fileExt =
System.IO.Path.GetExtension(fileUpload.FileName);
if (fileUpload.PostedFile != null && fileExt == ".csv")
{
try
{
//fileUpload.PostedFile.SaveAs(ConfigurationManager.AppSettings + appDataPath + "\\" + strFileNameOnServer);
fileUpload.PostedFile.SaveAs(Server.MapPath("~/Uploaded"));
//string appPath = HttpContext.Current.Request.ApplicationPath;
// string physicalPath = HttpContext.Current.Request.MapPath("~/MajorProject");
Label1.Text = "File name: " +
fileUpload.PostedFile.FileName + "<br>" +
fileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
fileUpload.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "Error saving <b>" + strFileNameOnServer + "</b><br>. " + ex.Message;
}
BtnImport1.Visible = true;
Cancel.Visible = true;
fileUpload.Visible = false;
btnUpload.Visible = false;
}
else
{
Label1.Text = "Error - a file name must be specified/only csv files are allowed";
return;
}
var data = File.ReadAllLines(Server.MapPath("~/Uploaded"))
.Select(line => line.Split(','))
.Select(columns => new {GuestName = columns[0], Guest_ID = columns[1], IC_Number = columns[2]});
myGridView.DataSource = data;
myGridView.DataBind();
}
Do I have to add new items into my aspx file? Like a label to display the error lines? The contents of the csv file has Name, Ic Number and also House. If so, can anyone show me the codes to do this?
You could check for missing values on GridView.RowDataBound event for yours myGridview.
Example:
void myGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Check if any of the values of mygridview row cells are empty.
if (e.Row.Cells[0].Text == "")
{
e.Row.Cells[0].Text = "ERROR: Guest name is empty!"
e.Row.Cells[0].Attributes.CssStyle.Add(HtmlTextWriterStyle.Color, "red");
}
if (e.Row.Cells[1].Text == "")
{
e.Row.Cells[1].Text = "ERROR: Guest Id is empty!"
e.Row.Cells[1].Attributes.CssStyle.Add(HtmlTextWriterStyle.Color, "red");
}
if (e.Row.Cells[2].Text == "")
{
e.Row.Cells[2].Text = "ERROR: Ic number is empty!"
e.Row.Cells[2].Attributes.CssStyle.Add(HtmlTextWriterStyle.Color, "red");
}
}
}
Don't forget to declare it inside gridview properties:
<asp:GridView ID="myGridview"
runat="server"
OnRowDataBound="myGridView_RowDataBound">
</asp:GridView>