How to Pass Values Between Pages? - c#

I am doing Airline Reservation System using GUI with ASP.NET in C#.
What I want is assign seats for user, after a user assign that seats, that seat cannot be assigned by others again. I try to use increment do this but instead of 1+1 = 2(that means seat number 2 is the next to be assigned), the system gives me 1+1=11. How can I do what I want?
I have 5 interfaces for this, and I need this assigned value stored in whole running process.
This is my code for the reservation button, I have 2 for it, First Class and Economy Class. Only 5 seats for First Class and 15 seats for Economy Class.
How can I do ?
protected void Button1_Click(object sender, EventArgs e)
{
Session["seats"] = "First Class";
if (firstseatnum > 5)
{
MessageBox.Show("Sorry, the first class seats was fully booked. Can you change to economy class?");
Response.Redirect("reservation.aspx");
}
else
{
++firstseatnum;
totalseatnum1 = Convert.ToInt32(firstseatnum+seatnum);
Response.Redirect("~/information.aspx?firstseatnum="+firstseatnum+"&seatnum="+totalseatnum1);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Session["seats"] = "Economy Class";
if (economyseatnum > 20)
{
MessageBox.Show("Sorry, the economy class seats was fully booked. Can you change to first class?");
Response.Redirect("reservation.aspx");
}
else
{
++economyseatnum;
totalseatnum2 = Convert.ToInt32(economyseatnum + seatnum);
Response.Redirect("information.aspx?economyseatnum=" + economyseatnum + "&seatnum="+totalseatnum2);
}
}
Please help me, thank you.

There are several ways to do it:
Query
// Set
var myVariable = "MyData";
Response.Redirect("/NextPage?MyVariable=" + myVariable);
// Get
var data = Request.QueryString["MyVariable"];
Cookie
// Set
var cookie = new HttpCookie("MyVariable");
cookie.Value = "NyData";
Response.Cookies.Add(cookie);
Response.Redirect("/NextPage");
// Get
var data = Request.Cookies["MyVariable"].Value;
Session
// Set
Session["MyVariable"] = "MyData";
Response.Redirect("/NextPage");
// Get
var data = Session["MyVariable"];
Application (Store Entire Process)
// Set
Application["MyVariable"] = "MyData";
Response.Redirect("/NextPage");
// Get
var data = Application["MyVariable"];
Also check CodeProject article to see more examples and detailed explanation.

Presumably seatnum is a string.
If so, try
totalseatnum1 = firstseatnum + Convert.ToInt32(seatnum);
and
totalseatnum2 = economyseatnum + Convert.ToInt32(seatnum);

Related

I messed up a "While" loop... Can i fix it?

I tryed to make a while loop, and i know the problem, i just have no idea how to fix it. The int I use just never updates, making the code useless... I use Visual Studio, windows fom app, if that changes something... Sorry for the lenght, but i don't know where's the problem. (Input 1 and 2 are textboxes...) The text file I use looks like this:
Username: new line
(costum text) new line
Password: new line
(costum text) new line
Username: new line
...
Here's the code:
public partial class Form1 : Form
{
//This is part of the problem
int search = 0;
//This is part of the problem (end)
public void OK_Click(object sender, EventArgs e)
{
string path = #"filePath.txt";
var count = File.ReadLines(path).Count();
string user = File.ReadLines(path).Skip(search + 1).Take(1).First();
string pass = File.ReadLines(path).Skip(search + 3).Take(1).First();
//Main problem
if (Input1.Text != "" && Input2.Text != "")
{
while (Input1.Text == user && Input2.Text == pass)
{
if (search < count)
{
search = search + 4;
}
}
if (search < count)
{
MessageBox.Show("worked");
search = 0;
}
}
//Main problem (end)
}
}
This can be greatly simplified. The usernames and passwords are on alternating lines, so they need to be declared inside of the loop. You can also use a for loop to control skipping to the next username/password combination at the end of each iteration of the loop. And you don't need to do File.ReadLines multiple times, that causes it to hit the disk multiple times for something you could just hold in memory once.
You should also rename your textboxes to have names that represent the data they should contain. So UsernameTextbox instead of Input1 for example.
public void OK_Click(object sender, EventArgs e)
{
string path = #"filePath.txt";
var fileLines = File.ReadLines(path);
var authenticatedSuccessfully = false;
for (int line = 0; line < fileLines.Length - 1; line += 2)
{
var user = fileLines[line];
var password = fileLines[line + 1];
if (UsernameTextbox.Text == user && PasswordTextBox.Text == pass)
{
authenticatedSuccessfully = true;
break;
}
}
if (authenticatedSuccessfully)
{
MessageBox.Show("You are logged in!");
}
else
{
MessageBox.Show("Incorrect username or password!");
}
}
Of course...you should keep in mind that this is not secure at all. In the real world, passwords should be one way hashed and salted. Then when a user wants to authenticate you hash the password again and compare it to the stored value. If they match, then they provided the correct password. Storing passwords in plaintext is not a good idea.
Your while condition is wrong. You can use for loop for that(using counters), or you need to rebuild your while loop. You must put if conditions inside While loop dont make them separate. https://www.w3schools.com/cs/cs_while_loop.asp. Using while loop is good chance to go for infinite. So I am using For loops all the times.

Property Data Not Outputing to Controls

In one of my current projects, I have been attempting to develop a system that will take data input from textboxes on one form, and input them into a list on another form so that they may be displayed via a listbox and labels on another form as a data reference for manual input into a database.
//Create Attendance Report Instance
AttendanceReport report = new AttendanceReport();
private void inputButton_Click(object sender, EventArgs e)
{
try
{
//Declare Variables
string administratorVerify = verificationBox.Text;
//Inputs Change Based on NewStudent Check
if (passwordInput.Text == passwordTextBox.Text)
{
//Save Changes
Save();
}
Relevant Section => else if (newStudentCheck.Checked == true)
{
//New Verification Instance
VerificationClass verify = new VerificationClass();
//Verification Gateway
if (verify.Verify(administratorVerify) == true)
{
//Send Student to Attendance Report List
report.DisplayStudent();
}
else
{
MessageBox.Show("Unauthorized Password\nOnly Authorized Administrators May Access this Function");
}
}
//Clear Inputs
clearInputs();
}
I designed the part of the program that retrieves the data and displays it to function off of an universal instance of the second form, calling an instance of the first form to retrieve the data. I originally had the program create a new instance of the second form whenever the input button was clicked, before I moved the instantiation out of that block, making it a universal instance.
List<NewStudent> studentList = new List<NewStudent>();
private void RetrieveStudentInfo(NewStudent student)
{
//Temp Variables
int ID;
int Grade;
//Create MainForm Instance
MainForm reference = new MainForm();
//Get Values
student.Class = reference.classBox.Text;
student.Name = reference.nameBox.Text;
if (int.TryParse(reference.idBox.Text, out ID))
{
student.ID = ID;
}
else
{
MessageBox.Show("Invalid ID");
}
student.Password = reference.createPasswordBox.Text;
student.District = reference.districtBox.Text;
student.Country = reference.countryBox.Text;
if (int.TryParse(reference.gradeBox.Text, out Grade))
{
student.Grade = Grade;
}
else
{
MessageBox.Show("Invalid Grade");
}
}
public void DisplayStudent()
{
//Create Object
NewStudent student = new NewStudent();
//Get Student Info
RetrieveStudentInfo(student);
//Add Object to List
studentList.Add(student);
//Add Entry to Selection
newStudentSelection.Items.Add(student.ID);
}
private void newStudentSelection_SelectedIndexChanged(object sender, EventArgs e)
{
//Get Selected Item
int index = newStudentSelection.SelectedIndex;
//Display Data
classOutput.Text = studentList[index].Class;
nameOutput.Text = studentList[index].Name;
idOutput.Text = studentList[index].ID.ToString();
passwordOutput.Text = studentList[index].Password;
districtOutput.Text = studentList[index].District;
gradeOutput.Text = studentList[index].Grade.ToString();
countryOutput.Text = studentList[index].Country;
}
For all my life, from where I stand it seems like this program should work. I Intellisense is giving me no styntax errors, and I have attempted to review my logic with fellow amateur programmers in person, but for what ever reason, the data will not output to the controls on the second form. The only I can think of is that somehow by reference variables I pass as arguments to my RetrieveStudentInfo method and such are not actually getting passed somehow, but that shouldn't be correct.
Any advice on this situation would be greatly appreciated.

Storing value from try for use in second try C#

Good day fellow helpers, i have following problem:
(running MS Visual Community Edition 2015)
private void button4_Click(object sender, EventArgs e) // Senden
{
serialPort2.WriteLine("SR,00,002\r\n");
textBox1.Text = "gesendet";
textBox3.Text = "";
try
{
System.IO.StreamReader file = new System.IO.StreamReader("C:\\blub.txt");
String line = file.ReadToEnd();
string Hallo = line; \\in the beginning there is "0" in the file
file.Close();
decimal counter = Convert.ToDecimal(Hallo); \\just for testing
counter++;
string b = serialPort2.ReadLine();
string[] b1 = Regex.Split(b, "SR,00,002,"); \\cuts off unwanted input from device
decimal b2 = decimal.Parse(b1[1]); \\number like -3000
System.IO.StreamWriter test = new System.IO.StreamWriter("C:\\blub.txt");
test.WriteLine(counter);
test.Close();
textBox7.Text = "Das ist counter:" + counter;
}
catch (TimeoutException)
{
textBox3.Text = "Timeout";
throw;
}
}
Now, the Serialport is a device that returns a lengthmeasurment. As it is a bit weird, or just the way its build it start with a negitve number (between -5000 and -3370). Now as i want to get measurement on the screen that is realistic i want to set the value to 0 and calculate the difference.
Means: I start the programm - press send - get a value (say -3000) - press send again (after pushing the seonsor in) and get the value that its been pushed in > 0 by adding the difference to 0.
I only learned to store values externally when i had a C course a year back like i did within my programm. Is there a way to store the value from the first measurement in the programm so i can use it on the next send/try?
The counter was just for testing and I would exchange it for the "decimal b2"
I hope there is an easy fix for that, not really a pro with C# yet but i'm eager to learn. I thank the willing helpers in advance, MfG, Chris
OK, I will simplify this in order to show concept so it will not have all the code you are actually using.
So, what you want is to click on button, get some values and store them for next click.
Value is stored in variable. If you have variable in function that is handler for click event, as soon as function completes execution, value will be destroyed.
So, what you need is to create variable in outer scope (class level). Your function is already in class of the form so let's get to code:
class Form1
{
string BetweenClickStorage;
private void button4_Click(object sender, EventArgs e)
{
//Load data here
BetweenClickStorage = LoadedData;
}
}
After this, when you click again on the button, value will still be in BetweenClickStorage. It will be also available to all other buttons click handlers and other code in that form.
If I'm understanding your question correctly, the answer is simply to declare a variable outside the try/catch:
//declare variable //
var measurement;
// TRY #1 //
try
{
//assign value to the variable here
}
catch
{
}
// TRY #2 //
try
{
// reference variable here
}
catch
{
}

Compare and calculate first, second, and third place

I am trying to figure out the most efficient way to calculate first, second, and third place for a simple C# program in which the purpose is to find the winner, 2nd place, and 3rd place and show their names accordingly however, my code seems way to large for such a simple task. I am new and I an using If statements to complete the required calculation but, I know there is a better way. Can someone enlighten me?
Here is my current code and where I stopped after realizing the amount a code this is going to take.
private void calculateButton_Click(object sender, EventArgs e)
{
// Define Name and Time Variables
string runnerone = runnerOneNameTextBox.Text; // Runner One Name
string runnertwo = runnerTwoNameTextBox.Text; // Runner Two Name
string runnerthree = runnerThreeNameTextBox.Text; // Runner Three Name
double runnerOneTime = double.Parse(runnerOneTimeTextBox.Text); // Runner One Time
double runnerTwoTime = double.Parse(runnerTwoTimeTextBox.Text); // Runner Two Time
double runnerThreeTime = double.Parse(runnerThreeTimeTextBox.Text); // Runner Three Time
//-------------------------------------------------------------------------
// Start of the If statement to calculate who is first, second, and third.
//-------------------------------------------------------------------------
// FIRST PLACE CODE:
if (runnerOneTime > runnerTwoTime && runnerOneTime > runnerThreeTime) // Runner One is greater than everyone
{
firstPlaceLabel.Text = runnerOneNameTextBox.Text;
firstPlaceTrophyLabel.Text = runnerOneNameTextBox.Text;
}
else if (runnerOneTime == runnerTwoTime && runnerOneTime > runnerThreeTime) // Runner one is equal to runner two
{
firstPlaceLabel.Text = runnerOneNameTextBox.Text;
firstPlaceLabel.Text = runnerTwoNameTextBox.Text;
firstPlaceTrophyLabel.Text = runnerOneNameTextBox.Text;
firstPlaceTrophyLabel.Text = runnerTwoNameTextBox.Text;
}
else if (runnerOneTime > runnerTwoTime && runnerOneTime == runnerThreeTime)
}
}
}
You have a list of three runners, so let the .NET list sorting functionality come to your rescue:
private class RunnersAndTimes
{
public string Name {get};
public double Time {get};
public RunnersAndTimes(string name, double time)
{
Time = time;
Name = name;
}
}
...
private void calculateButton_Click(object sender, EventArgs e)
{
var runnersAndTimes = new List<RunnersAndTimes> {
new RunnersAndTimes(runnerOneNameTextBox.Text,
double.Parse(runnerOneTimeTextBox.Text)),
new RunnersAndTimes(runnerTwoNameTextBox.Text,
double.Parse(runnerTwoTimeTextBox.Text)),
new RunnersAndTimes(runnerThreeNameTextBox.Text,
double.Parse(runnerThreeTimeTextBox.Text))
};
var orderedRunners = runnersAndTimes.OrderBy(runner => runner.Time).ToList();
firstPlaceLabel.Text = orderedRunners[0];
secondPlaceLabel.Text = orderedRunners[1];
thirdPlaceLabel.Text = orderedRunners[2];
}

C# WinForm + Barcode Scanner input, TextChanged Error

UPDATE: SOLUTION AT END
I have a Winform, label1 will display some info returned from a SQL Search using the input (MemberID) received from barcode scanner via txtBoxCatchScanner.
Scenario is people swiping their MemberID Cards under the scanner as they pass through reception and the Winform automatically doing a Search on that MemberID and returning their info including for example "Expired Membership" etc on the receptionist's PC which has the winForm in a corner of her desktop.
I have the Below Code working fine on first swipe (eg. first person)
The number MemberID, for example 00888 comes up in the text box, ADO.NET pulls the data from SQL and displays it fine.
one thing to note maybe, the cursor is at the end of the memberID: 00888|
All good so far, THEN:
when swipe 2 (eg. next person) happens
their number (say, 00999) gets put onto the end of the first in the txtBox eg: 0088800999 so naturally when TextChanged Fires it searches for 0088800999 instead of 00999 ....
I've tried:
txtBoxCatchScanner.Clear();
and
txtBoxCatchScanner.Text = "";
and
reloading the form
at the end of my code to "refresh" the text box
but i guess they trigger the TextChanged Event
How can i refocus or ... clear the old number and cursor back to start of txtBox after the previous swipe has done its stuff...
I'm a beginner so I'm sure the code below is pretty crap....
But if anyone has time, please let me know how fix it to do what i want.
UPDATE:
Ok after much experimenting I''ve managed to get this 1/2 working now hopefully someone more experience can help me to completion! :P
if (txtBoxCatchScanner.Text.Length == 5)
{
label1.Text = txtBoxCatchScanner.Text; // just a label for testing .. shows the memmber ID
txtBoxCatchScanner.Select(0, 5);
}
SO scan 1, say 00888 , then that gets highlighted, scan 2 , say 00997 ... sweet! overwrites (not appends to) 00888 and does it's thing ... scan 2 0011289 ... DOH!!
Problem: not all barcodes are 5 digits!! they are random lengths!! Memeber ID range from 2 digit (eg. 25) to 10 digits, and would grow in the future...
Edit: Something I've discovered that is that the barcodes are read as indvidual key presses. I think this is why answer 1 below does not work and while the big probmlems:
for example with 00675 the input (?output) from the scanner is:
Down: Do
Up: Do
Down: Do
Up: Do
Down: D6
Up: D6
Down: D7
Up: D7
Down: D5
Up: D5
down: Retunn
Up: Return
other info: barcode scanner is: an Opticon OPL6845 USB
Thanks
private void txtBoxCatchScanner_TextChanged(object sender, EventArgs e)
{
Member member = new Member();
member.FirstName = "";
member.LastName = "";
//Get BarCode
//VALIDATE: Is a Number
double numTest = 0;
if (Double.TryParse(txtBoxCatchScanner.Text, out numTest))
{
//IS A NUMBER
member.MemberID = Convert.ToInt32(txtBoxCatchScanner.Text);
//SEARCH
//Search Member by MemberID (barcode)
List<Member> searchMembers = Search.SearchForMember(member);
if (searchMembers.Count == 0)
{
lblAlert.Text = "No Member Found";
}
else
{
foreach (Member mem in searchMembers)
{
lblMemberStatus.Text = mem.MemberStatus;
lblMemberName.Text = mem.FirstName + " " + mem.LastName;
lblMemberID.Text = mem.MemberID.ToString();
lblMessages.Text = mem.Notes;
if (mem.MemberStatus == "OVERDUE") // OR .. OR .. OR ...
{
lblAlert.Visible = true;
lblAlert.Text = "!! OVERDUE !!";
//PLAY SIREN aLERT SOUND
//C:\\WORKTEMP\\siren.wav
SoundPlayer simpleSound =
new SoundPlayer(#"C:\\WORKTEMP\\siren.wav");
simpleSound.Play();
}
else
{
lblAlert.Visible = true;
lblAlert.Text = mem.MemberStatus;
}
}
}
}
else
{
//IS NOT A NUMBER
lblAlert.Text = "INVALID - NOT A NUMBER";
////
//lblMemberName.Text = "";
//lblMemberID.Text = "";
//lblMemberID.Text = "";
}
SOLUTION:
The System won't let me answer my own question for another 3 hours, as I'm a newbie only 1 post, so will put here:
First thanks everyone for your help and Patience.
I Have finally figured a solition, not fully tested yet as its 2am and bed time.
following along from my updates where I had success but hit the variable length of MemberID problem. I've now overcome that with the Code below:
namespace SCAN_TESTING
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void txtBoxCatchScanner_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)Keys.Return)
{
e.Handled = true;
int barcodeLength = txtBoxCatchScanner.TextLength;
txtBoxCatchScanner.Select(0, barcodeLength);
//TEST
label3.Text = barcodeLength.ToString();
//TEST
label2.Text = txtBoxCatchScanner.Text;
}
}
I'll add this to my previous "real" code and test in the morning
But at this stage is doing exactly what I want! =]
Update: Tested it .. works exactly what needed:
private void txtBoxCatchScanner_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)Keys.Return)
{
e.Handled = true;
int barcodeLength = txtBoxCatchScanner.TextLength;
txtBoxCatchScanner.Select(0, barcodeLength);
//
//INSERT ORGINAL CODE HERE. No Changes were needed.
//
}//end of if e.KeyValue ...
}//end txtBoxCatchScanner_KeyUp
Hope that helps anyone in the future!! :)
Thanks again for the 2 very good solutions, I can see how they work, and learnt alot.
Just didn't work in my case - more likely due to myself or my error/not understanding, or scanner type.
I´m not exactly sure what the actual problem is.
txtBoxCatchScanner.Clear();
txtBoxCatchScanner.Text = "";
both trigger the "Changed" Event.
But they also clear the box. So that should be what you want to do.
You could check at the beginning if the box is actually empty, and return in case it is. Like:
if(txtBoxCatchScanner.Text == "" |txtBoxCatchScanner.Text == string.Empty)
return;
So nothing else happens, if the box is empty.
If I misunderstood your problem, please specify and I will try to help.
Regards
EDIT:
Your function should work if it looked something like this:
private void txtBoxCatchScanner_TextChanged(object sender, EventArgs e)
{
Member member = new Member();
member.FirstName = "";
member.LastName = "";
if(txtBoxCatchScanner.Text == "" | txtBoxCatchScanner.Text == string.Empty)
return; // Leave function if the box is empty
//Get BarCode
//VALIDATE: Is a Number
int numTest = 0;
if (int.TryParse(txtBoxCatchScanner.Text, out numTest))
{
//IS A NUMBER
//member.MemberID = Convert.ToInt32(txtBoxCatchScanner.Text);
member.MemberID = numTest; // you already converted to a number...
//SEARCH
//Search Member by MemberID (barcode)
List<Member> searchMembers = Search.SearchForMember(member);
if (searchMembers.Count == 0)
{
lblAlert.Text = "No Member Found";
}
else
{
foreach (Member mem in searchMembers)
{
lblMemberStatus.Text = mem.MemberStatus;
lblMemberName.Text = mem.FirstName + " " + mem.LastName;
lblMemberID.Text = mem.MemberID.ToString();
lblMessages.Text = mem.Notes;
if (mem.MemberStatus == "OVERDUE") // OR .. OR .. OR ...
{
lblAlert.Visible = true;
lblAlert.Text = "!! OVERDUE !!";
//PLAY SIREN aLERT SOUND
//C:\\WORKTEMP\\siren.wav
SoundPlayer simpleSound =
new SoundPlayer(#"C:\\WORKTEMP\\siren.wav");
simpleSound.Play();
}
else
{
lblAlert.Visible = true;
lblAlert.Text = mem.MemberStatus;
}
}
}
}
else
{
//IS NOT A NUMBER
lblAlert.Text = "INVALID - NOT A NUMBER";
////
//lblMemberName.Text = "";
//lblMemberID.Text = "";
//lblMemberID.Text = "";
}
txtBoxCatchScanner.Clear();
}
The barcode scanner you use seems to function as a HID - a keyboard emulation. Every simple barcode scanner I know (and I'm working with them on a daily basis) has the option of specifying a suffix for the scanned barcode. Change the suffix to CRLF and add a default button to your form. Scanning a barcode that ends with CRLF will then automatically "push the button".
Move the code that performs the checks from TextChanged event in to the event handler for the buttons Click event and remove the TextChanged event handler. Then, when the button is clicked, also clear the text box and set the focus back to the text box.
You should be good to go, now.
You can easily check whether the barcode scanner already has the correct suffix configured: Open up Notepad and scan some barcodes. If they all appear on separate lines, then everything's fine. Otherwise you'll need to scan some configuration barcodes from the scanner's manual.
To sum it all up, this should be the code for the button's Click event:
private void btnCheckMember_Click(object sender, EventArgs e)
{
Member member = new Member();
member.FirstName = "";
member.LastName = "";
string memberText = txtBoxCatchScanner.Text.Trim();
txtBoxCatchScanner.Text = String.Empty;
int numTest = 0;
if (String.IsNullOrEmpty(memberText) ||!Int32.TryParse(memberText, out numTest))
{
//IS NOT A NUMBER
lblAlert.Text = "INVALID - NOT A NUMBER";
return;
}
member.MemberID = numTest;
List<Member> searchMembers = Search.SearchForMember(member);
if (searchMembers.Count == 0)
{
lblAlert.Text = "No Member Found";
}
else
{
foreach (Member mem in searchMembers)
{
lblMemberStatus.Text = mem.MemberStatus;
lblMemberName.Text = mem.FirstName + " " + mem.LastName;
lblMemberID.Text = mem.MemberID.ToString();
lblMessages.Text = mem.Notes;
if (mem.MemberStatus == "OVERDUE") // OR .. OR .. OR ...
{
lblAlert.Visible = true;
lblAlert.Text = "!! OVERDUE !!";
SoundPlayer simpleSound = new SoundPlayer(#"C:\\WORKTEMP\\siren.wav");
simpleSound.Play();
}
else
{
lblAlert.Visible = true;
lblAlert.Text = mem.MemberStatus;
}
}
}
This solution avoids the following problems:
The event being triggered upon every character added/removed from the content of the text box (which is also the case when scanning a barcode: They are added one by one as if they were entered on a keyboard)
Resulting from 1. the problem that a member check is performed upon every entered character
Resulting from 2. the problem that member XYZ will never be found if there is a member XY in the database, as the check stops after finding XY
Resulting from 3. the problem that member XY will also not be found, but only member Z, because in 3. the text box is cleared and Z is the only character being entered.
The best way to clear the textBox on the next textChange event.
Insert this line
txtBoxCatchScanner.SelectAll();
at the end of TextChange function.. This will select the text, so that i can be replaced easily on the next event.

Categories

Resources