So I'm trying to make a simple banking website using C# and ASP.net and I'm just learning about Session Variables for the first time. I have a starting account balance of 1000 dollars and I want to transfer that to another page and have that balance updated via withdrawals or deposits and then update the balance. Heres my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Project4.Forms
{
public partial class Services : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click1(object sender, EventArgs e)
{
double userInput = double.Parse(txtAmount.Text);
Session["userInput"] = userInput;
Session["balance"] = 1000.00;
double balance = Convert.ToDouble(Session["balance"]);
Session["userAction"] = ddlSelectService.SelectedItem.Text;
if (ddlSelectService.SelectedItem.Text == "Withdrawl")
{
balance -= userInput;
}
else if (ddlSelectService.SelectedItem.Text == "Deposit")
{
balance += userInput;
}
else
{
}
Response.Redirect("Status.aspx");
}
}
}
I understand the root of my problem is probably the original Session["balance"] = 1000.00; but I'm not sure how to declare a starting amount and then it not affect the balance when I return to this page from the results page. Any help is appreciated, also as I said in the beginning this is a barebones simple atm website please don't suggest anything too crazy because I am a beginner.
I don't do asp.net, so this is just a guess, but maybe try only setting the default value if it's null, something like: if (Session["balance"] == null) Session["balance"] = 1000;. It also seems like this should be in the Page_Load event, not the btnSubmit_Click event, since it only has to happen once.
Finally, don't forget to update the session variable after setting the new balance:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["balance"] == null) Session["balance"] = 1000;
}
protected void btnSubmit_Click1(object sender, EventArgs e)
{
double userInput;
if (!double.TryParse(txtAmount.Text, out userInput))
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert",
"alert('Input must be a valid double');", true);
return;
}
Session["userInput"] = userInput;
double balance = Convert.ToDouble(Session["balance"]);
Session["userAction"] = ddlSelectService.SelectedItem.Text;
if (Session["userAction"] == "Withdrawl")
{
balance -= userInput;
}
else if (Session["userAction"] == "Deposit")
{
balance += userInput;
}
Session["balance"] = balance;
Response.Redirect("Status.aspx");
}
Related
I have a program where a user fills in a form and hits calculate, then when the user hits summary it will show all the users that have entered in data. When more users enter data, they are simply added to the summary using the same lbl (lblUsers) the only problem I am having is being able to delete the most recent entry into the summary which would be the newest made label.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LifeInsurance
{
public partial class frmMain : Form
{
double commissionRate;
double insuranceAmount;
double totalAmount;
int numberOfCustomers;
double totalInsuranceDollars;
double totalCommission;
private void btnClearAll_Click(object sender, EventArgs e)
{
lblUsers.Text = "";
}
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
insuranceAmount = int.Parse(txtInsuranceAmount.Text);
}catch (Exception)
{
MessageBox.Show("You must enter all details");
}
if(insuranceAmount>= 1000)
{
commissionRate = 0.005;
totalAmount = insuranceAmount * 0.005;
}
if (insuranceAmount >= 100000)
{
commissionRate = 0.0010;
totalAmount = insuranceAmount * 0.0010;
}
if (insuranceAmount >= 1000000)
{
commissionRate = 0.0015;
totalAmount = insuranceAmount * 0.0015;
}
totalInsuranceDollars += totalAmount;
totalCommission += commissionRate;
numberOfCustomers += 1;
lblUsers.Text += "Name: "+txtFirstName.Text +" "+ txtLastName.Text+"
"+ "Payout Amount: "+totalAmount+Environment.NewLine;
lblUsers.Text += "Total Policies: " + numberOfCustomers+" " + "Total
Insurance Dollars Earned: " + totalInsuranceDollars+" " + "Total
Commission Earned: " + totalCommission+Environment.NewLine;
}
private void btnSummary_Click(object sender, EventArgs e)
{
lblUsers.Visible = true ;
}
private void btnClear_Click(object sender, EventArgs e)
{
//remove one label
}
}
}
I'm sorry, if I understand correctly you want your Label to show all but the last entry when the user clicks "Summary" is that correct? So in your screenshot it shows 3 entries, but you want only 2 entries to be shown?
If so, see if this helps:
public static void btnSummary_Click(object sender, EventArgs e)
{
string currentText = lblUsers.Text;
int positionOfLastEntry = currentText.LastIndexOf("Name:");
string textWithoutLastEntry = currentText.Substring(0, positionOfLastEntry);
lblUsers.Text = textWithoutLastEntry;
lblUsers.Visible = true;
}
I fill the textboxes on page_load event.Then I edit textboxes data and tried to update data. Variables are assigned with old values. How can I do to get the new values.
Here is my code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class mymembertype : System.Web.UI.Page
{
public static int mem_typeid;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["valueid"] != null)
{
mem_typeid = (int)(Session["valueid"]);
string memtype_name = Convert.ToString(Session["valueName"]);
string rate = Convert.ToString(Session["rate"]);
txtmembtype.Text = Convert.ToString(memtype_name);
txtdscrate.Text = rate;
Insert_membertype.Text = "Update";
}
}
protected void Insert_membertype_Click(object sender, EventArgs e)
{
funtions fun = new funtions();
if (txtmembtype.Text != "" && txtdscrate.Text != "" )
{
if (Insert_membertype.Text == "Save")
{
string membetype = txtmembtype.Text;
int dscrate = Convert.ToInt32(txtdscrate.Text);
bool chk = fun.Insert_membertype(membetype, dscrate);
if (chk)
lblInfo.Text = " saving membertype successful";
else
lblInfo.Text = "Error saving membertype";
}
else
{
string membetype = txtmembtype.Text;
int dscrate = Convert.ToInt32(txtdscrate.Text);
bool chk = fun.Update_memberType(mem_typeid, membetype, dscrate);
if (chk)
lblInfo.Text = " Updating membertype successful";
else
lblInfo.Text = "Error Updating membertype";
}
}
}
}
As you see second condition block is for updating data. But it have only values in page load.Now new data is assigned. Please ....
Your problem is that Page Load is called before the event handler for your controls. If you want to understand more about the order things happen in ASP.net just Google "ASP.Net Page Lifecycle" - if you're going to be doing a lot of development I recommend at least getting a basic understanding of what ASP.Net is doing.
You'll want to change your page load to check if the current request is a postback.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && Session["valueid"] != null)
{
// Doing stuff
}
}
The "IsPostBack" variable is false the first time the page is loaded, and then is true for every subsequent load.
Try if(!IsPostBack) method in Pageload event
You need to write the code inside page_load under IsPostback condition like below to get the updated values
if (!IsPostBack)
{
// Bind your code here
}
write a code GetData Method.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData();
}
}
public void GetData()
{
}
I am trying to create a page using object oriented design in C#. I wanted to use same instance object all the time in my page but it is not working .
Below is my code :
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataSource1.Delete();
}
}
protected void ViewBalance_Click(object sender, EventArgs e)
{
string tempString = Request.Form["BalanaceField"];
double bal;
Double.TryParse(tempString, out bal);
Session["CurrentBalance"] = bal;
BankAccount newAcc = new BankAccount(bal);
resultDiv.InnerHtml = "<h1> Current Balance is $" +
newAcc.getCurrentBalance() + "</h1>";
transactionDiv.Style["display"] = "block";
newAccountDiv.Style["display"] = "none";
}
protected void Withdraw_Click(object sender, EventArgs e)
{
string currentBal = Session["CurrentBalance"].ToString();
double bal;
Double.TryParse(currentBal, out bal);
BankAccount newAcc = new BankAccount(bal);
double withdrwaAmount;
Double.TryParse(Request.Form["WithdrawField"], out withdrwaAmount);
if (newAcc.validWithDraw(withdrwaAmount))
{
newAcc.withDraw(withdrwaAmount);
Session["CurrentBalance"] = newAcc.getCurrentBalance();
insertRecord("Withdaw", withdrwaAmount, newAcc.getCurrentBalance());
resultDiv.InnerHtml =
"<h1>Amount Withdrwan Succesfully. Current Balance is $ " +
newAcc.getCurrentBalance() + "</h1>";
}
else
{
resultDiv.InnerHtml =
"<h1>You cann't ovewdraw you account. Your current Balance is $" +
bal + " and you are trying to widthdraw $" +
withdrwaAmount + " </h1>";
}
}
protected void Deposit_Click(object sender, EventArgs e)
{
string currentBal = Session["CurrentBalance"].ToString();
double bal;
Double.TryParse(currentBal, out bal);
BankAccount newAcc = new BankAccount(bal);
double depositAmount;
Double.TryParse(Request.Form["DeopositField"], out depositAmount);
double newBalance = newAcc.deposit(depositAmount);
Session["CurrentBalance"] = newBalance;
insertRecord("Deposit", depositAmount, newAcc.getCurrentBalance());
resultDiv.InnerHtml =
"<h1>Amount Deposit Succesfully. Current Balance is $ " +
newAcc.getCurrentBalance() + "</h1>";
}
protected void InterestCount_Click(object sender, EventArgs e)
{
string currentBal = Session["CurrentBalance"].ToString();
double bal;
Double.TryParse(currentBal, out bal);
BankAccount newAcc = new BankAccount(bal);
double interestMonths;
Double.TryParse(Request.Form["MonthsField"], out interestMonths);
double interest = bal * (0.10) * (interestMonths / 12);
resultDiv.InnerHtml =
"<h1>Total amount with acculmated Interest would be $ " +
(newAcc.getCurrentBalance() + interest) +
" and Interest would be $:" + interest + "</h1>";
}
public void insertRecord(string type, double amount, double finalAMount)
{
DataView dv =
(DataView) SqlDataSource1.Select(DataSourceSelectArguments.Empty);
int id = dv.Count + 1;
SqlDataSource1.InsertParameters.Add("Id", id.ToString());
SqlDataSource1.InsertParameters.Add("Type", type);
SqlDataSource1.InsertParameters.Add("Amount", amount.ToString());
SqlDataSource1.InsertParameters.Add("Balance", finalAMount.ToString());
SqlDataSource1.Insert();
}
}
As we can see I have to always create new instance of BankAccount class in each method.
Ideally I would like just one object for entire page and reuse it when needed.
Reading your code it won't make any difference in performance. Your page is created (an object of class _Default is instantiated) with every request.
There are some possibilities:
Declare the field private or protected above your methods, at class level. But as you use this object only in Click methods you will have one BankAccount object per request, which you already have. (will not increase performance, nor reduce memory usage)
You can declare the field static, but you will have the same object for all the users on your website (you don't want someone to see a wrong balance if two requests are performed at the same time).
You can store the bank account object on session and use it, if you don't want to create it every time. (will increase memory usage, you will also use performance, as the object is serialized, deserialized and a cast must be performed)
Why do you want to do this ? Performance will not be better and the memory usage will not be optimized.
Place your definition for BankAccount newAcc just above protected void Page_Load(object sender, EventArgs e) (do some research on "scope" to understand why this works)
Inside Page_Load create your first instance
newAcc = new BankAccount(); //note that you'll want a constructor that doesn't have a balance argument
Make sure you have a public way of modifying the balance field, then when you need to change the balance:
newAcc.balance = whatever;
I'm creating a simple patients billing program using Asp.net c#. Now, I have a dropdownlist with items "Ward" , "Semi Private" and "Private" If the user would choose ward the textbox below it would automatically be 700, if Semi Private it should be 1000 and if Private it should be 2000. I also have a textbox under it indicating how many days the patient stayed, the user is the one who should input the days, and for example he's from the ward room and the days he stayed was 3 then the computation should be 700 * 3. I also have a textbox that will display the answer. I hope u guys understand the things I explained above. So far, here are my codes:
Default.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.Text == "Ward")
{
TextBox4.Text = "700";
}
if (DropDownList1.Text == "Semi Private")
{
TextBox4.Text = "1000";
}
if (DropDownList1.Text == "Private")
{
TextBox4.Text = "2000";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
First of all add an attribute in your asp tag for dropdownlist like-
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
Then in the event, write the following code-
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.ToString();
if(selected == "Ward")
{
int NetAmount = 700 * 3; //you can use any int variable in place of "3" as well
TextBox1.Text = NetAmount.ToString();
}
else if(selected == "Semi Ward")
{
TextBox1.Text = "1000";
}
else
{
TextBox1.Text = "2000"
}
}
That's it. Hope it will help.
AHHHHH ok this is driving me nuts.
Why when does my decimal point in the wrong place e.g.
if i have the string 567 in the textbox and click the decimal button i would expect (or i want) the textbox to change to 567. but instead i get .567
It only goes into the correct place when i add another number e.g. if i had the number 4 then straight after doing the above I'd get 567.4
Edit:
Heres my whole code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Calculator
{
public partial class frmCurrencyCalc : Form
{
public frmCurrencyCalc()
{
InitializeComponent();
}
private void cmdZero_Click(object sender, EventArgs e)
{
if (txtScreen.Text == "0")
{
txtScreen.Text = "0";
}
else
{
txtScreen.AppendText("0");
}
}
private void cmd1_Click(object sender, EventArgs e)
{
if (txtScreen.Text == "0")
{
txtScreen.Text = "1";
}
else
{
txtScreen.AppendText("1");
}
}
private void cmdTwo_Click(object sender, EventArgs e)
{
if (txtScreen.Text == "0")
{
txtScreen.Text = "2";
}
else
{
txtScreen.AppendText("2");
}
}
private void cmdThree_Click(object sender, EventArgs e)
{
if (txtScreen.Text == "0")
{
txtScreen.Text = "3";
}
else
{
txtScreen.AppendText("3");
}
}
private void cmdFour_Click(object sender, EventArgs e)
{
if (txtScreen.Text == "0")
{
txtScreen.Text = "4";
}
else
{
txtScreen.AppendText("4");
}
}
private void cmdFive_Click(object sender, EventArgs e)
{
if (txtScreen.Text == "0")
{
txtScreen.Text = "5";
}
else
{
txtScreen.AppendText("5");
}
}
private void cmdSix_Click(object sender, EventArgs e)
{
if (txtScreen.Text == "0")
{
txtScreen.Text = "6";
}
else
{
txtScreen.AppendText("6");
}
}
private void cmdSeven_Click(object sender, EventArgs e)
{
if (txtScreen.Text == "0")
{
txtScreen.Text = "7";
}
else
{
txtScreen.AppendText("7");
}
}
private void cmdEight_Click(object sender, EventArgs e)
{
if (txtScreen.Text == "0")
{
txtScreen.Text = "8";
}
else
{
txtScreen.AppendText("8");
}
}
private void cmdNine_Click(object sender, EventArgs e)
{
if (txtScreen.Text == "0")
{
txtScreen.Text = "9";
}
else
{
txtScreen.AppendText("9");
}
}
private void cmdDecimal_Click(object sender, EventArgs e)
{
txtScreen.AppendText(".");
cmdDecimal.Enabled = false;
}
private void cmdCancel_Click(object sender, EventArgs e)
{
txtScreen.Text = "0";
cmdDecimal.Enabled = true;
}
}
}
The RightToLeft looks to be your problem.
As described in MSDN,
The RightToLeft property is used for
international applications where the
language is written from right to
left, such as Hebrew or Arabic. When
this property is set to
RightToLeft..::.Yes, control elements
that include text are displayed from
right to left.
As one ofthe previous answers suggested, this should be set to false, but with TextAlign set to Right to mimic the appearance of a real calculator.
My advice is -- define a business layer. In your case -- a double variable. Upon button clicks, update the variable first. Then format the value.
My advice is to set TextAlign to Right, but leave RightToLeft set to No.
Edit: Having said that, this issue may be unrelated to these settings.
I remember a friend having this a bug similar to this back in early 2009 in Visual Studio 2008 on Windows Vista. Strangely enough, the same problem did not occur on the same version of Visual Studio on Windows XP.
If you haven't updated Visual Studio / .NET 3.5 to Service Pack 1, I suggest doing that and seeing if it fixes the problem.
Perhaps try a different method:
private void AddDecimal()
{
txtScreen.SelectionLength = txtScreen.TextLength;
txtScreen.SelectedText += ".";
}
(Also is your text box, text aligment, right aligned... if not that may contribute to your problem.)
I think you have a few things here.
By the looks of it, you've set:
txtScreen.right to left = true;
If you append just the decimal point, you get the result you describe. Try using something like:
txtScreen.AppendText(".00");
This will give you the result you are describing.
You could be opening a can of worms. When you start formatting the textbox, you are changing it from holding a value to presentation. Eg:
decimal value = 567;
txtScreen.Text = value.ToString("0.00");
Then you will have to start writing crazy validation rules to avoid values like 567.00.1 etc.
Just to let you all know who are interested.
I managed to fix it somehow. All I did was delete the right to left thing in the design code and then realigned it (using the GUI) to right and its worked...odd as I did nothing different to last time...
Oh well
Thank you all for your help
Much aprreciated
x
You can try this one, it works for me:
private void btndot_Click(object sender, EventArgs e)
{
if (txtbox.Text == "0" && txtbox.Text != null)
{
txtbox.Text = ".";
}
else
{
txtbox.Text = txtbox.Text + ".";
}
}