Class is not returning an object - c#

it's not recognizing my lstSectionNumber (Tickets.TicketForm.lastSectionNumber is inaccessible due to its protection level). Hopefully I explained everything clearly, I'm just recently started learning C#, any help would be appreciated. Thank you in advance.
public class TicketOrder
{
private static int premiumTicket = 40;
private static int basicTicket = 20;
private static int serviceCharge = 2;
private TicketForm form = new TicketForm();
public double CalcTicketCost(int section, double quantity)
{
double amount = 0;
if (int.Parse(form.lstSectionNumber.SelectedItem.Value) <= 150)
{
amount = (quantity*premiumTicket) + (quantity*serviceCharge);
return amount;
}
else
{
amount = (quantity*basicTicket) + (quantity*serviceCharge);
}
return amount;
}
}
Code-behind:
public partial class TicketForm : System.Web.UI.Page
{
int myInt;
public const double premiumTicket = 40;
public const double basicTicket = 20;
public const double serviceCharge = 2;
TicketUser user = new TicketUser();
TicketOrder order = new TicketOrder();
protected void Page_Load(object sender, EventArgs e)
{
// This disables the unobtrusive validation in order to see the result
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
// This will keep my five numbers in my list box without adding more with a refresh of a page
if (!IsPostBack)
{
Random RandomSection = new Random();
for (int i = 0; i < 5; i++)
{
// Created a list box with five random numbers from 1 to 300
myInt = RandomSection.Next(1, 300);
lstSectionNumber.Items.Add(myInt.ToString());
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// I also added TextMode="Number"to my <asp:TextBox ID="txtNumberOfTickets"
// runat="server" Height="18px" Width="134px"></asp:TextBox> code in order
// to get rid of an error incase I left my txtNumberOfTicket empty
int section = Convert.ToInt32(lstSectionNumber.SelectedValue);
double ticketQuantity = Convert.ToInt32(txtNumberOfTickets.Text);
//This label displays users first and last names, number of tickers, seat section number and ticket price
lblPrice.Text = txtFirstName.Text + " " +
txtLastName.Text + ", " +
txtNumberOfTickets.Text + " " +
"Tickets in Section:" + " " +
lstSectionNumber.SelectedValue + "," +
" Total Cost is: " +
order.CalcTicketCost(section, ticketQuantity).ToString("C");
}
protected void btnCreateAccount_Click(object sender, EventArgs e)
{
user.firstName = txtFirstName.Text;
user.lastName = txtLastName.Text;
user.username = txtUserName.Text;
lblCreateAccount.Text = user.CreateAccount();
}
}

Simply give your constructor an empty body
change
public TicketOrder()
to
public TicketOrder() { }
TO solve your other problem, you are trying to make a NEW page, but asp.NET has already made a page for this page load and populated the values for you. You should Pass the current page object into your TicketOrder constructor and save instead.
Like so:
public TicketOrder(TicketForm form)
{
this.form = form;
}
and change in TicketOrder
private TicketForm form = new TicketForm();
to
private TicketForm form;
and change in TicketForm
TicketOrder order = new TicketOrder();
to
TicketOrder order;
public TicketForm()
{
this.order = new TicketOrder(this);
}

Well, I figured it out.
if (section <= 150)
{ amount = (quantity * premiumTicket) + (quantity * serviceCharge);
return amount;

Related

Injection of radiobuttonlist selected value into class

I want to create a webform with 4 types of phones like: LG, xiaomi, samsung and iphone. They will be in an Array and I will insert them into dynamic radiobuttonList in the page init.
Also, the user will have a textbox where he will put an amount of money he has. The user will also have a button that will calc if he have the budget for the selected phone from the list.
After the user selects the phone, write in the budget and press the button
he will get "in budget" or "not enough budget".
The class have property of the array to insert the all the array from the page init and will have 2 functions:
One function will take the budget number > will go to the 2nd function that will see the selected phone and the budget > do its calcs and return the result into the 1st func that will give the feedback.
Now where I am stuck:
if the class isnt made global - and i put it in init or in button click - it wont work, so im looking for a way to make it work but without putting it global
so far i managed to inject the selected value into a class property and than compare - but i want to know if there is a way that this can happen with array inside class property
maybe if anyone can help me out and refer me to a guide where i can learn more about this subject (how inject selected value into function of a class and etc) ill be glad! as everything i see is C# with console but i work with ASP.NET WEB APPLICATION (.netframework)
enter code here
namespace gfjsr{
public partial class WebForm1 : System.Web.UI.Page{
phone InsertUserInfo = new phone();
protected void Page_init(object sender, EventArgs e){
string[] myArr = new string[] { "samsung", "IPHONE", "XIAOMI","LG"};
RadioButtonList phoneList = new RadioButtonList();
phoneList.ID = "radioList";
for (int i = 0; i< myArr.Length; i++)
{
ListItem li = new ListItem();
li.Text = myArr[i];
li.Value = i.ToString();
phoneList.Items.Add(li);
}
Panel1.Controls.Add(phoneList);
Label budgetLb = new Label();
budgetLb.ID = "budglb";
budgetLb.Text = "write your budget";
Panel1.Controls.Add(budgetLb);
TextBox insertBudg = new TextBox();
insertBudg.ID = "budgTxt";
Panel1.Controls.Add(insertBudg);
Button myBtn = new Button();
myBtn.ID = "btn1";
myBtn.Click += new EventHandler(btn1_click);
myBtn.Text = "result";
Panel1.Controls.Add(myBtn);
Label Labelfeedback = new Label();
Labelfeedback.ID = "feedback";
Labelfeedback.Text = "";
Panel1.Controls.Add(Labelfeedback);
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn1_click(object sender, EventArgs e)
{
InsertUserInfo.phoneChosen = ((RadioButtonList)FindControl("radioList")).SelectedItem.Text;
double UserBudget =
Convert.ToDouble(((TextBox)FindControl("budgTxt")).Text);
InsertUserInfo.BudgetYN(UserBudget);
((Label)FindControl("feedback")).Text = InsertUserInfo.feedback; }}}
namespace gfjsr{
public class phone{
private string _phoneChosen;
public string phoneChosen
{
get { return _phoneChosen; }
set { _phoneChosen = value; }
}
private string _feedback;
public string feedback
{
get { return _feedback; }
set { _feedback = value; }
}
public double Func1(string x)
{
double phonePrice = 0;
if( x == "samsung")
{
phonePrice = 4000;
}
if (x == "IPHONE")
{
phonePrice = 3500;
}
if (x == "XIAOMI")
{
phonePrice = 3000;
}
if (x == "LG")
{
phonePrice = 2000;
}
return phonePrice;
}
public void BudgetYN(double y)
{
if(y >= Func1(_phoneChosen))
{
_feedback = "positive";
}
else
{
_feedback = "no";
}
}
}
}

values a re not being displayed in TextBox

in this program, when the Recall button (recallBtn_Click()) is clicked, it calls a method (that calculates directions) from another class which should then call the showPath() method. the show path method should then display its output in a textBox. But the values don't show even though i can see from debugging that the values are being sent to the text box. can anybody tell me where i went wrong?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
storeRetSelect.SelectedIndex = 0;
PrioritySelect.SelectedIndex = 0;
}
public void showPath(List<PathFinderNode> mPath)
{
var T = new Form1().directionsTextBox;
foreach (PathFinderNode node in mPath)
{
if ((node.X - node.PX) > 0) { T.Text += "Right" + System.Environment.NewLine ; }
if ((node.X - node.PX) < 0) { T.Text += "Left" + System.Environment.NewLine; }
if ((node.Y - node.PY) > 0) { T.Text += "UP" + System.Environment.NewLine; }
if ((node.Y - node.PY) < 0) { T.Text += "Down" + System.Environment.NewLine; }
}
}
private void recallBtn_Click(object sender, EventArgs e)
{
var path = new pathPlan();
string desigString = inputTextBox.Text;
int[] desig = new int[3];
for (int i = 0; i < desigString.Length; i++) { desig[i] = (int)char.GetNumericValue(desigString[i]); }
path.Recall(desig[1], desig[2], (-1) * desig[0]);
}
}
With this line you are initialising a new object and get the reference of the textbox there.
var T = new Form1().directionsTextBox;
But I assume you want to use the textbox of the form which is allready open. Change the line to the following to access the textbox of the current object.
var T = this.directionsTextBox;

freezing form after clicking button

I have a problem regarding to payment button.
I don't encounter an error before building, but after building and clicking the payment button it hangs. I think its because of lblTotalPrice.text, but I don't know how to fix it.
public partial class Form1 : Form
{
int totalCost;
public double holDer;
public Form1()
{
InitializeComponent();
this.cbo1.Items.AddRange(new object[] { "Lechon Kawali - 200", "Bicol Express - 300"
,"Adobo - 350" });
}
private void btnAdd_Click(object sender, EventArgs e)
{
lb1.Items.Add(cbo1.SelectedItem);
lb1.SelectedIndex = lb1.SelectedIndex ;
int z = 0;
if (cbo1.SelectedIndex == 0)
{
z = z + 1;
}
if (cbo1.SelectedIndex == 1)
{
z = z + 2;
}
if (cbo1.SelectedIndex == 2)
{
z = z + 3;
}
switch(z)
{
case 1:
totalCost = totalCost + 200;
break;
case 2:
totalCost = totalCost + 300;
break;
case 3:
totalCost = totalCost + 350;
break;
}
lblSubTotalCost.Text = ("Php " + totalCost.ToString());
}
private void btnDelete_Click(object sender, EventArgs e)
{
int deleteCost = 0;
int itemCost = 0;
foreach (int selectedIndex in lb1.SelectedIndices)
{
itemCost = int.Parse(lb1.Items[selectedIndex].ToString().Split('-')[1]);
deleteCost += itemCost; lb1.Items.RemoveAt(selectedIndex);
}
totalCost = totalCost - deleteCost;
lblSubTotalCost.Text = ("Php " + totalCost.ToString());
lb1.Items.Remove(lb1.SelectedItem);
if (lb1.Items.Count > 0)
{
lb1.SelectedIndex = 0;
}
else
MessageBox.Show("No orders");
}
private void lblVAT_TextChanged(object sender, EventArgs e)
{
Add();
}
private void lblSubTotalCost_TextChanged(object sender, EventArgs e)
{
multiply();
Add();
}
public void multiply()
{
int a;
double b = 0.12;
bool Valid = int.TryParse(totalCost.ToString(), out a);
if (Valid)
lblVAT.Text = (a * b).ToString();
else
lblVAT.Text = "No VAT entered";
}
private void lbTotalPrice_TextChanged(object sender, EventArgs e)
{
Add();
}
public void Add()
{
int a;
int b;
bool AValid = int.TryParse(totalCost.ToString(), out a);
bool BValid = int.TryParse(lblVAT.Text, out b);
if (AValid && BValid)
{
lblTotalPrice.Text = ("Php " + (a + b).ToString());
}
}
private void btnPayment_Click(object sender, EventArgs e)
{
holDer = double.Parse(tbPayment.Text) - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
}
As you stated in your comments, your problem it is not that your application hangs, but the problem is that you are getting a Input string was not in a correct format Exception.
That it seems is from this block:
private void btnPayment_Click(object sender, EventArgs e)
{
holDer = double.Parse(tbPayment.Text) - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
As it is a not very complex code, your problem seems to be when you are casting your textboxes to Double. Be sure that you are using the correct separator for double values and that you not have any strange characters in tbPayment
Try using TryParse method:
double res;
if(double.TryParse(tbPayment.Text, out res))
{
holDer = res - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
else
{
MessageBox.Show("Input a correct format");
}
I suspect it's because the lblTotalPrice_TextChanged event-handler calls Add() which then changes the lblTotalPrice.Text property, causing the event to fire again, ad -infinitum?

C# bowling calculator. Array of classes returning null

I am working on a project in c# visual studio in which i am attempting to make a bowling calculator. i have made a class for frames which contains a throw1 and throw2. I first fill the array of classes with one button and calculate score after game completion. when i go to calculate score it tells me i have null values.below is my form code the class is just
class frames
{
public int intThrow1;
public int intThrow2;
}
the main form is
public partial class Form1 : Form
{
frames[] frame = new frames[11];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int intFrst = int.Parse(textBox1.Text);
int intScnd = int.Parse(textBox2.Text);
if (lbxScorecard.Items.Count <= 21)
{
int intIndx = 0;
if (intFrst == 10)
{
frame[intIndx] = new frames();
frame[intIndx].intThrow1 = intFrst;
frame[intIndx].intThrow2 = 0;
lbxScorecard.Items.Add(frame[intIndx].intThrow1);
lbxScorecard.Items.Add(frame[intIndx].intThrow2);
intIndx += 2;
}
else
{
frame[intIndx] = new frames();
frame[intIndx].intThrow1 = intFrst;
frame[intIndx].intThrow2 = intScnd;
lbxScorecard.Items.Add(frame[intIndx].intThrow1);
lbxScorecard.Items.Add(frame[intIndx].intThrow2);
intIndx++;
}
}
else
{
MessageBox.Show("max throws");
}
}
private void button2_Click(object sender, EventArgs e)
{
int intScore = 0;
for (int index = 0; index <= 11; index++)
{
if (frame[index].intThrow1 == 10 && index < 9) // here is where it throws a null exception stating the index may be empty
{
if (frame[index + 1].intThrow1 != 10)
{
intScore = intScore + frame[index].intThrow1 + frame[index + 1].intThrow1 + frame[index + 1].intThrow2;
}
else if (frame[index].intThrow1 == 10)
{
intScore = intScore + frame[index].intThrow1 + frame[index + 1].intThrow1 + frame[index + 2].intThrow1;
}
}
else if (frame[index].intThrow1 + frame[index].intThrow2 == 10 && index < 9) //it was throwing the same exception here until i added && index<9 in the if statements.
{
intScore = intScore + frame[index].intThrow1 + frame[index].intThrow2 + frame[index + 1].intThrow1;
}
else
{
intScore = intScore + frame[index].intThrow1 + frame[index].intThrow2;
}
}
MessageBox.Show(intScore.ToString());
}
}
Problem is:
frames[] frame = new frames[11];
You also need to instantiate each element of the array like you did in the button1_Click function:
frame[intIndx] = new frames();
Also note that you have a class variable frame and the same one in button2_Click which is probably a bad idea.

c# windows form application dynamic objects value

i have made a mistake of re-inventing the wheel. There are options
but somehow i like the feel of this.
Sorry but don't have enough rep to post an image.
This is how the form looks like:
SNO.-------ITEMS--------FROM--------TO---------QUANTITY // labels
[ 1 ]-------[-----------▼]---[--------]----[--------]------[-------------] {NEW} {DELETE} //textboxes and buttons
I've got the 'new' button click event to generate a row, and serial number to be automatic
and inserted the items into the collections from Properties panel.
Delete button deletes an entire row and shifts both the button up on Y position.
I need to assign the value of quantity [(TO - FROM ) + 1] in the QUANTITY text boxes,
for which i have the code as :
public void print_quant(object Sender, EventArgs e)
{
TextBox quanty;
quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0];
calculate_quant(this, e);
quanty = result;
}
public static string result;
public string calculate_quant(object sender, EventArgs e)
{
TextBox sfrom;
sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0];
TextBox sto;
sto = (TextBox)this.Controls.Find("STO" + count, true)[0];
TextBox quan;
quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0];
//if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text))
{
int to = Convert.ToInt32(sto.Text);
int from = Convert.ToInt32(sfrom.Text);
int quantity = (to - from) + 1;
result = quantity.ToString();
quan.Text = result;
}
return result;
}
count is initialized at 1 on form load, keeps increasing with number of rows
the same code works in the delete row method
public void delete_row(object sender, EventArgs e) //function to delete a row
{
TextBox snum;
snum = (TextBox)this.Controls.Find("SNO"+count, true)[0];
snum.Dispose();
...//delete other row elements
}
please help me figure out why it doesnt work for the print_quant / calculate_quant methods
I made some changes to your code. I changed the return on your calculate method to a string, and added a quanty.Text=calculatemethod line to your print method
public void print_quant(object Sender, EventArgs e)
{
TextBox quanty;
quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0];
//add this line
quanty.Text = calculate_quant(this, e).ToString();
}
public static string result;
//change this
//public void calculate_quant(object sender, EventArgs e)
//to
public string calculate_quant(object sender, EventArgs e)
{
TextBox sfrom;
sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0];
TextBox sto;
sto = (TextBox)this.Controls.Find("STO" + count, true)[0];
//this isn't being used here
//TextBox quan;
//quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0];
//if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text))
{
int to = Convert.ToInt32(sto.Text);
int from = Convert.ToInt32(sfrom.Text);
int quantity = (to - from) + 1;
return quantity.ToString();
}
}
Edit
try this.
Create a usercontrol and make it look exactly like one of your rows.
add a property variable for each of the boxes
//whenever you Sno="something" the textbox will automatically be updated.
private string _Sno="00000";
public string Sno{get{return _Sno;}set{_sno=value; SnoTextBox.Text=value;}}
do this for each of your textboxes.
on your main form now you can add a flowpanel, they a bit tricky at first. when you add your new Usercontrol to it, they will automatically be added from the top down, or up, or however you set it up.
When you want to add a new row, just add your new Usercontrol to the flowpanel
FlowPanel flowPanel =new FlowPanel();
FlowPanel.Controls.Add(new myUserControl());
to delete
FlowPanel.Controls.RemoveAt(2);
This is really poorly written, but I am out of time. Either ignore me altogether, or try to figure it out. Sorry I couldn't be more help.
this worked for me
private void textBox_TextChanged(object sender, EventArgs e)
{
TextBox quant;
int x = count - 1;
string num = Convert.ToString(x);
quant = (TextBox)this.Controls.Find("QUANTITY" + x , true)[0];
TextBox to = (TextBox)this.Controls.Find("STO" + x, true)[0];
TextBox from = (TextBox)this.Controls.Find("SFRM" + x, true)[0];
string tovalue = to.Text;
int to1 = Convert.ToInt32(tovalue);
string fromvalue = from.Text;
int from1 = Convert.ToInt32(fromvalue);
int result = (to1 - from1) + 1 ;
if (result > 0)
{
string result1 = Convert.ToString(result);
quant.Text = result1;
}
}
after adding
STO.TextChanged += new System.EventHandler(textBox_TextChanged);
at the function that was generating the boxes where i needed to calculate :)

Categories

Resources