Using function in ASP.NET web application - c#

Excuse me guys, i'm a beginner in c# and needed help and some guidance in creating a calculator web app.
So i was given a task to create a calculator web app using the ASP.NET web application web form with the UI looking like this:
Calculator UI
The thing is, i made a mistake and made it using Windows Forms App (WFA) instead and i could get the calculator to work.
But when i tried to make the calculator using the ASP.NET web application web form the calculator won't work because somehow the variable that i set to run the method didn't get any value unlike when i run it in the WFA.
Here is my code:
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
bool lastpressedIsOperation;
string input = String.Empty;
protected void num_Click(object sender, EventArgs e)
{
Button button = sender as Button;
//this.display.Text = "";
input+=button.Text;
if (display.Text == "0" && display.Text != null)
{
display.Text = button.Text;
}
else
{
display.Text += button.Text;
}
}
protected void op_Click(object sender, EventArgs e)
{
Button button = sender as Button;
input+=button.Text;
if (display.Text == "0" && button.Text == "-" && display.Text != null)
{
display.Text = button.Text;
}
else
{
display.Text += button.Text;
}
}
protected void del_Click(object sender, EventArgs e)
{
//this.display.Text = input.ToString(0,input.Length);
}
protected void del_all_Click(object sender, EventArgs e)
{
this.display.Text = "0";
this.input = string.Empty;
}
private void enter_Click(object sender, EventArgs e)
{
string inFix = input;
string isValid = Validate(inFix);
string rpn = ConvertToPostFix(isValid);
string result = Convert.ToString(CalculateRPN(rpn));
this.display.Text = result;
input = result;
}
private static string Validate(string inFix)
{
StringBuilder newstring = new StringBuilder(inFix);
Stack<int> lb_index = new Stack<int>();//stack for left bracket index
Queue<int> rb_index = new Queue<int>();//stack for right bracket index
char temp = '#';
Console.WriteLine("temp: ", temp);
for (int i = 0; i < newstring.Length; i++)
{
if (newstring[i] == '(')
lb_index.Push(i);
else if (newstring[i] == ')')
rb_index.Enqueue(i);
Console.WriteLine("temp: {0}", temp);
if (newstring[i] == '-')//change unary - to ~
{
if (temp.IsOperator())
{
newstring[i] = '~';
}
}
temp = newstring[i];
}
if (lb_index.Count == rb_index.Count)
{
bool bracket_valid = true;
for (int i = 0; i < lb_index.Count; i++)
{
if (lb_index.Pop() > rb_index.Dequeue())
{
bracket_valid = false;
break;
}
}
if (bracket_valid != true)
{
newstring.Clear();
newstring.Append("Error, Bracket wrong");
}
}
else if (lb_index.Count < rb_index.Count || lb_index.Count > rb_index.Count)
{
newstring.Clear();
newstring.Append("Error, Bracket wrong");
}
Console.WriteLine("newstring = {0}", newstring);
return newstring.ToString();
}
The idea is i want to get the string from textbox after the user inputted the value using number and operation buttons and pressed the enter button.
The string is then validated first using Validate(inFix), then formatted into postfix ConvertToPostFix(isValid), which then calculated using CalculateRPN(rpn).
But i dont know why the isValid variable never get the value from Validate(inFix) which cause the other methods not working. Is there some difference on how to use the function in ASP Web app form? If so, how do i use method/function in this?
And is there any better way to implement this so i can fulfill my task?

I believe your problem is that you are setting:
string inFix = input;
In your
enter_Click
method.
Yet, the
input
variable is initialized to:
string input = String.Empty;
So, each time the form is loaded, i.e. on an initial load or a postback, the input variable is re-initialized to an empty string.
I'll not reinvent the post here, but to resolve this, you need to do something like:
Session["INPUT"] = input;
whenever input is modified, and do something like:
input = (string)Session["INPUT"];
To initialize the input variable on the page load.
If it is the initial page load, the input variable will be null (i.e. the session variable Session["INPUT"] does not exist).
Basically, what I am saying is that, while the asp.net session stores the state of controls on the forms, it does not save the state of your own class variables that you add to the page.

Related

Application freezes when I click on button to go to another form in winforms

private void subjectpagenextbtn_Click(object sender, EventArgs e)
{
TextBox[] subjectnamearray = new TextBox[] { subjectname1, subjectname2, subjectname3, subjectname4, subjectname5, subjectname6 };
int i = 0;
while (i <= numofsubjects.SelectedIndex)
{
if (subjectnamearray[i].Text.Trim() == string.Empty)
{
MessageBox.Show("Please fill out all textboxes.", "Error Message");
i = i + 1;
return;
}
}
i = 0;
string[] subjects = new string[numofsubjects.SelectedIndex];
List<string> datatablesubjectnamearray = new List<string>();
this.Hide();
var TaskPage = new Task_Page(subjectnamearray,datatablesubjectnamearray,numofsubjects.SelectedIndex);
TaskPage.Closed += (s, args) => this.Close();
TaskPage.Show();
TaskPage.StartPosition = FormStartPosition.Manual;
TaskPage.Location = new Point(this.Location.X, this.Location.Y);
while (i < numofsubjects.SelectedIndex)
{
datatablesubjectnamearray.Add(subjectnamearray[i] + "Weighting");
datatablesubjectnamearray.Add(subjectnamearray[i] + "Marks");
/*http://csharp.net-informations.com/collection/list.htm*/
i = i + 1;
}
Task_Page taskpage = new Task_Page(subjectnamearray, datatablesubjectnamearray, numofsubjects.SelectedIndex);
}
This is the code for one of my buttons on a form that I have that collects the subjects of the users and number of subjects for users and I basically also made an array for the titles for the datatable that I'm going to create on the next form. I'm also passing the values,subjectnamearray, datatablesubjectnamearray, numofsubjects.SelectedIndex to TaskPage. So, Task Page is the page that I want to get to when I click the button. I also want these values to be passed but when I click on the button, it just freezes and I can't even close the application. I have to press the stop button on visual studio. But I don't know why it's freezing.
Your first while loop appears to be the issue. You get caught in infinite loop. I do not see any other issues further down in the code.
Your code looks like this:
private void subjectpagenextbtn_Click(object sender, EventArgs e)
{
TextBox[] subjectnamearray = new TextBox[] { subjectname1, subjectname2, subjectname3, subjectname4, subjectname5, subjectname6 };
int i = 0;
while (i <= numofsubjects.SelectedIndex)
{
if (subjectnamearray[i].Text.Trim() == string.Empty)
{
MessageBox.Show("Please fill out all textboxes.", "Error Message");
i = i + 1;
return;
}
}
I think if you changed your code to this:
private void subjectpagenextbtn_Click(object sender, EventArgs e)
{
TextBox[] subjectnamearray = new TextBox[] { subjectname1, subjectname2, subjectname3, subjectname4, subjectname5, subjectname6 };
int i = 0;
while (i <= numofsubjects.SelectedIndex)
{
if (subjectnamearray[i].Text.Trim() == string.Empty)
{
MessageBox.Show("Please fill out all textboxes.", "Error Message");
return;
}
i = i + 1;
}
It should fix your issue with visual studio crashing. If it does not I would recommend closing VS, restarting your computer and trying again. Good Luck!

Button is not getting the ViewState Value and no error message shown

i have been trying to use the ViewState object to store the counter for clicking the ImageButton.For instance if ImageButton1 is click it will store the counter == 1(or increment) in it if another button is clicked the counter will become null.I tried clicking the imagebutton , the counter becomes 1 however when i try to retrieve from the submit button via the if else statement it retrieves nothing and the button cannot work.In addition no error message has been shown.I am developing something like a seat selector for my project.Any help will be greatly appreciated!.Below are the codes
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (ImageButton1.ImageUrl != "~/Images/bed-occupied.png")
{
ImageButton1.ImageUrl = "~/Images/bed-occupied.png";
if (ViewState["Counter"] == null)
{
counterBed1 = 1;
TextBoxClass.Text = counterBed1.ToString();
}
else
{
counterBed1 = (int)ViewState["Counter"] + 1;
}
}
else
{
ImageButton1.ImageUrl = "~/Images/bed-unoccupied.png";
ViewState["Counter"] = null;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
ViewState["Counter"] = counterBed1;
// if(ViewState["Counter"] != null)
if(counterBed1 ==1)
{
Panel_ErrorMsg.Visible = true;
lb_ErrorMsg.Text = "Patient Successfully admitted to hospital";
}
}
You are incrementing the value as well as setting a local variable but please note you are never storing the value back in ViewState object.
int counterBed1 = 0;
if (ImageButton1.ImageUrl != "~/Images/bed-occupied.png")
{
ImageButton1.ImageUrl = "~/Images/bed-occupied.png";
if (ViewState["Counter"] == null)
{
counterBed1 = 1;
TextBoxClass.Text = counterBed1.ToString();
ViewState["Counter"] = counterBed1; // Add This
}
else
{
counterBed1 = (int)ViewState["Counter"] + 1;
ViewState["Counter"] = counterBed1; //Add This
}
}
else
{
ImageButton1.ImageUrl = "~/Images/bed-unoccupied.png";
ViewState["Counter"] = null;
}
Also, don't use class variable as it will be re-initialized after every new request, use local variable instead like this in Submit Button handler:-
protected void btnSubmit_Click(object sender, EventArgs e)
{
int counterBed1 = Convert.ToInt32(ViewState["Counter"]);
// if(ViewState["Counter"] != null)
if(counterBed1 ==1)
{

Select a particular line in textbox?

I have a two forms, 1 and 2. Form1 has one textbox and form2 has a textbox and button. I want to go to a specified line, meaning that when I enter the value of form2's textbox then my mouse cursor goes to form1's textbox.
private void button1_Click(object sender, EventArgs e)
{
int line = Form1.ab;
for (int i = 1; i < line; i++)
{
if (i == Convert.ToInt16( textBox1.Text))
{
// fr.textbox1 is a textbox form1 and
// textbox1.text is a textbox of the form1
fr.textBox1.SelectionStart =
int.Parse( textBox1.Text) ;
fr.textBox1.ScrollToCaret();
break;
}
}
}
The TextBox.GetFirstCharIndexFromLine method finds the index of the first character of a line.
So your selection starts there. Then find the end of that line, which is Environment.NewLine or the end of the text.
Since the line number is entered by the user you should use int.TryParse to handle invalid input.
private void button1_Click(object sender, EventArgs e)
{
int lineNumber;
if (!int.TryParse(textBox2.Text, out lineNumber) || lineNumber < 0)
{
textBox1.Select(0, 0);
return;
}
int position = textBox1.GetFirstCharIndexFromLine(lineNumber);
if (position < 0)
{
// lineNumber is too big
textBox1.Select(textBox1.Text.Length, 0);
}
else
{
int lineEnd = textBox1.Text.IndexOf(Environment.NewLine, position);
if (lineEnd < 0)
{
lineEnd = textBox1.Text.Length;
}
textBox1.Select(position, lineEnd - position);
}
}
Apply this logic to your code, and recode it as you need.
private void button1_Click(object sender, EventArgs e)
{
if (textBox_Form1.Text.Contains(textBox_Form2.Text))
{
textBox_Form1.Focus();
textBox_Form1.SelectionStart = textBox_Form1.Text.IndexOf(textBox_Form2.Text);
textBox_Form1.SelectionLength = textBox_Form2.Text.Length;
}
}
try something like;
int lineNumber = Form1.ab;
// split the contents of the text box
string text = textBox1.Text;
string[] lines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
if (lineNumber < 0 || lineNumber > lines.Length)
{
MessageBox.Show("The line number is does not exist");
return;
}
// get the character pos
int selStart = 0;
for (int i = 0; i < (lineNumber - 1); i++)
{
selStart += lines[i].Length + Environment.NewLine.Length;
}
textBox1.Focus();
textBox1.SelectionStart = selStart;
textBox1.SelectionLength = lines[lineNumber - 1].Length;
Note: you can access the other text box directly in the other form by going to the Form2 designer, clicking the text box and going to Properties. In the Properties dialog, look for a property called Modifiers and change the value to internal or public. This will allow you to access the text box value in the other form directly like so;
private void Form1_Load(object sender, EventArgs e)
{
Form2 form2Instance = new Form2();
string sampleText = form2Instance.textBox1.Text;
}
If you need to know further samples on how to access controls/details on other forms, let me know.
You are creating a NEW form1 where the textbox is likely to be blank, and calling GetPass() on that empty form. You need an instance of the already-opened form1 where the textbox might have a value. for more information
click here
Try the below code
var sdr = (System.Windows.Controls.TextBox) sender;
if (!string.IsNullOrEmpty(sdr.Text)) {
var start = sdr.Text.LastIndexOf(Environment.NewLine, sdr.CaretIndex);
var lineIdx = sdr.GetLineIndexFromCharacterIndex(sdr.CaretIndex);
var lineLength = sdr.GetLineLength(lineIdx);
sdr.SelectionStart = start + 1;
sdr.SelectionLength = lineLength;
sdr.SelectedText.Substring(0, sdr.SelectedText.IndexOf(Environment.NewLine) + 1);
Clipboard.SetText(sdr.SelectedText);
}
maybe this better:
{
...
string SelectedText = fr.textBox1.Lines[line];
int SelectedTextPos = fr.textBox1.Text.IndexOf(SelectedText);
int SelectedTextLen = SelectedText.Lenght;
fr.textBox1.Select(SelectedTextPos, SelectedTextLen);
fr.textBox1.ScrollToCaret();
...
}

.Net Webform losing data

I am having problems getting my page to maintain state. View state is enabled by default but everytime I click a button it resets the form. This is the code I have
protected void Page_Load(object sender, EventArgs e)
{
Levels loadGame = new Levels(currentGame);
int [] gameNums = loadGame.getLevelNums();
int inc = 1;
foreach(int i in gameNums){
if (i != 0)
{
TextBox tb = (TextBox)FindControl("TextBox" + inc);
tb.Text = i.ToString();
tb.Enabled = false;
}
else {
//leave blank and move to next box
}
inc++;
}
This is the initial load
protected void NormalButton_Click(object sender, EventArgs e)
{
clearBoxes();//clear boxes first
setCurrentGame("normal");//setting to normal returns normal answers
Levels loadGame = new Levels(returnCurrentGame());
int[] gameNums = loadGame.getLevelNums();
int inc = 1;
foreach (int i in gameNums)
{
if (i != 0)
{
TextBox tb = (TextBox)FindControl("TextBox" + inc);
tb.Text = i.ToString();
tb.Enabled = false;
}
else
{
//leave blank and move to next box
}
inc++;
}
}
Clicking this button changes the numbers in different boxes.
protected void Button1_Click(object sender, EventArgs e)
{
}
Then I have this empty button but everytime I click it, it resets the form even though I havent set it to do anything yet. I would like the boxes to stay the same and I would also like to keep the objects alive. I'm not sure what I'm missing but please point me in the right direction. Thanks in advance
The Page_Load event occurs every time the page is loaded, including event-driven postbacks (button clicks, etc).
It looks like initialization code is in your Page_Load, so when you click the button it runs again.
There are two options:
Put everything that you want to happen only on the FIRST load in a n if statement:
Move your initialization to Page_Init.
Code sample for the first option:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack) // Teis is the key line for avoiding the problem
{
Levels loadGame = new Levels(currentGame);
int [] gameNums = loadGame.getLevelNums();
int inc = 1;
foreach(int i in gameNums){
if (i != 0)
{
TextBox tb = (TextBox)FindControl("TextBox" + inc);
tb.Text = i.ToString();
tb.Enabled = false;
}
else {
//leave blank and move to next box
}
inc++;
}
}
}
Also, recommended reading: The ASP.NET Page Lifecycle

Check window for focus-Password Generator C#

For my end of year project I am creating a password generator where you generate a password, then you can choose whether or not you want to store it in a local compact DB(.sdf). I am working on the GUI at the moment. I am creating a strength bar for passwords but the problem is that I can't seem to have it update the strength bar without first moving the slider. Let me show you example of what I am talking about. I was wondering if I could do this with code or with action events. Tell me what you think. Below is some code for the GUI designer. Do you think this is a good idea or would there be a better way? The focus idea came from if the window has focus it would keep checking the options and see if anything has changed. Video: http://youtu.be/ihSeKbsL55M
namespace PasswordGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void fileToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void quitToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
private void bcopy_Click(object sender, EventArgs e)
{
if (passwordGenBox.Text.Length != 0)
{
Clipboard.SetText(passwordGenBox.Text);
}
else
{
MessageBox.Show("No Password Generated.", "Copy Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void bclear_Click(object sender, EventArgs e)
{
passwordGenBox.Text = "";
}
private void lengthSlider_Scroll(object sender, EventArgs e)
{
sliderLength.Text = lengthSlider.Value.ToString();
int str = lengthSlider.Value;
bool scheck = symCheck.Checked;
bool ncheck = numbersCheck.Checked;
//1-10 no symbols or numbers
if (str > 0 && str <= 10)
{
strLabel.Text = "Week";
}
//1-10 symbols no numbers
if (str > 0 && str <= 10 && scheck == true && ncheck == false)
{
strLabel.Text = "Alright";
}
//1-10 no symbols but numbers
if (str > 0 && str <= 10 && scheck == false && ncheck == true)
{
strLabel.Text = "Week";
}
//1-10 symbols & numbers
if (str > 0 && str <= 10 && scheck == true && ncheck == true)
{
strLabel.Text = "Okay";
}
}
private void bgen_Click(object sender, EventArgs e)
{
int pwlength = lengthSlider.Value;
bool symbols = false;
bool numbers = false;
if (symCheck.Checked && numbersCheck.Checked)
{
symbols = true;
numbers = true;
}
else if (symCheck.Checked && numbersCheck.Checked == false)
{
symbols = true;
numbers = false;
}
else if (symCheck.Checked == false && numbersCheck.Checked)
{
symbols = false;
numbers = true;
}
else
{
symbols = false;
numbers = false;
}
Generator gen = new Generator(pwlength, symbols, numbers);
}
}
}
Well, it's quite difficult to understand what you're actually asking here but the reason your ProgressBar isn't updating is that you're not actually telling it to update unless you move the slider.
Notice how you have all your logic for whether the password is "alright, weak or okay" on the Slide event of your "lengthSlider" component. However, nowhere in that code do you set the value of the ProgressBar - that appears to be done on the "bgen_Click" event which I assume is the generate password button?
In order to update the GUI when you operate the individual controls you need to call the appropriate code. I would suggest you put all your logic into meaningful functions and call them as needed.
Personally I'd have something along these lines:
GetPasswordStrengthString(); - check for symbols and numbers checkbox.checked and the length to return an appropriate string for the "strLabel" label.
CalculateStrengthBarLength(); - all your logic to determine the length of the ProgressBar
These would then be called wherever you want them to take effect. For example, on the CheckedChanged event of the symbols and numbers checkboxes as when that changes you want to see it reflected in the ProgressBar.

Categories