Injection of radiobuttonlist selected value into class - c#

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";
}
}
}
}

Related

How to make a scoring system in c# (Converting int to string and string to bool in c#)

I am trying to make a scoring system where if the user inputs 1 into the text box it outputs 4 into the listbox and so on. i've tried using Convert.Int32 and .ToString and bool.Parse Nothing has worked so far.
private void PlaceBox_TextChanged(object sender, EventArgs e)
{
BadForm.place = Convert.ToInt32(points);
points = Convert.ToInt32(PlaceBox.Text);
bool.Parse(PlaceBox.Text = 1.ToString());
if (PlaceBox.Text = 1.ToString())
{
PlaceBox.Text = 4;
}
else if (PlaceBox.Text = 2)
{
PlaceBox.Text = 3;
}
else if (PlaceBox.Text = 3)
{
PlaceBox.Text = 2;
}
else if (PlaceBox.Text = 4)
{
PlaceBox.Text = 1;
}
else
{
MessageBox.Show("ERROR");
}
}
Thats the code it's very basic but and that's just for one form

Rewriting my code as a Method, using C# Visual Studio

I am currently having trouble understanding Methods and how they work in C#. I currently have code written for a car cost calculator program I created, I want to rearrange or break my code down using methods. I am unsure how or where to begin doing so as it pertains to my program. Here is my code, clarification would be helpful! Thank you!
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//constants for the Zone entered by user
const decimal ZoneCostN = 27;
const decimal ZoneCostS = 36;
const decimal ZoneCostE = 45;
const decimal ZoneCostW = 54;
private void CalcButton_Click(object sender, EventArgs e)
{
//set the variables
decimal PackWeight = 0;
decimal CostZone = 0;
decimal CostWeight = 0;
decimal ShippingTot = 0;
decimal Net = 0;
const decimal PerPound = 18;
//parses the entry into the textboxes
decimal.TryParse(WeightText.Text, out PackWeight); ;
//algorithm for variables
CostWeight = PackWeight * PerPound;
Zonelbl.Text = "";
CostZone = 0;
//if else statement to get the zone cost
{
if (NorthButton.Checked)
{
CostZone = ZoneCostN;
}
else if (SouthButton.Checked)
{
CostZone = ZoneCostS;
}
else if (EastButton.Checked)
{
CostZone = ZoneCostE;
}
else if (WestButton.Checked)
{
CostZone = ZoneCostW;
}
else
{
MessageBox.Show("Select a zone!");
}
}
//algorithm to get total and net
ShippingTot = CostZone + CostWeight;
Net = ShippingTot / CostWeight;
//if condition for CAPPED label
if (ShippingTot >= 100)
{
CAPPEDlbl.Visible = true;
}
else
{
CAPPEDlbl.Visible = false;
}
//output for all the data
Zonelbl.Text = CostZone.ToString("c");
Weightlbl.Text = CostWeight.ToString("c");
Totallbl.Text = ShippingTot.ToString("c");
Netlbl.Text = Net.ToString("c");
}
private void ClearButton_Click(object sender, EventArgs e)
{
//clears the form
Zonelbl.Text = "";
Weightlbl.Text = "";
Totallbl.Text = "";
Netlbl.Text = "";
WeightText.Text = "";
CAPPEDlbl.Visible = false;
WeightText.Focus();
}
}
Usually, we create methods when we need to reuse a code. In your case, you should see which part of your code will be reused in the future. If it is a simple form you may don't need to change anything but imagine you want to use your clear functionality somewhere else, create a method and call it everywhere you need
void clear()
{
Zonelbl.Text = "";
Weightlbl.Text = "";
Totallbl.Text = "";
Netlbl.Text = "";
WeightText.Text = "";
CAPPEDlbl.Visible = false;
WeightText.Focus();
}
private void ClearButton_Click(object sender, EventArgs e)
{
clear();
}
Now you can reuse clear() and in case you needed to change it you only need to change the method. It's the concept and you can apply it wherever you need.

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;

Loop all textbox and collect values in c# asp.net

I'm trying to get a list of strings from the database.
For each string in the list i want to add a label & textbox to the page.
On button submit I want to collect the textbox value as well as the corresponding label value then save it to the database.
I need help retrieving the values from the textboxes.
What I have so far:
Panel1 is on the aspx page
protected List<string> items = MyClass.GetItems();
protected void Page_Load(object sender, EventArgs e)
{
GenerateItemsTable();
}
private void GenerateItemsTable()
{
Table table = new Table();
table.ID = "Table1";
//PlaceHolder1.Controls.Add(table);
Panel1.Controls.Add(table);
foreach (var x in items)
{
TableRow row = new TableRow();
for (int y = 0; y < 1; y++)
{
TableCell labelCell = new TableCell();
labelCell.Controls.Add(CreateLabel(x));
labelCell.CssClass = "tdLabel";
row.Cells.Add(labelCell);
TableCell txbCell = new TableCell();
txbCell.Controls.Add(CreateRadNumericTextBox(x));
txbCell.Width = 30;
row.Cells.Add(txbCell);
TableCell dataTypeCell = new TableCell();
dataTypeCell.Text = "<span style='font-size: 10px; color: #777'>(student count)</span>";
dataTypeCell.Width = 100;
row.Cells.Add(dataTypeCell);
TableCell fourthCell = new TableCell();
if (x == items[items.Count - 1])
{
RadButton rb = new RadButton();
rb.ID = "submit";
rb.Text = "Submit Guidance";
rb.Skin = "Forest";
rb.Click += new EventHandler(submit_Click);
rb.AutoPostBack = true;
fourthCell.Controls.Add(rb);
row.Cells.Add(fourthCell);
}
else
{
row.Cells.Add(fourthCell);
}
}
table.Rows.Add(row);
}
}
private RadNumericTextBox CreateRadNumericTextBox(string x)
{
RadNumericTextBox rntb = new RadNumericTextBox();
rntb.ID = x;
rntb.Width = 40;
return rntb;
}
private Label CreateLabel(string x)
{
Label l = new Label();
l.ID = "label_" + x;
l.Text = "<label>" + x + "</label>";
return l;
}
protected void submit_Click(object sender, EventArgs e)
{
foreach (Control x in FindControl("Panel1").FindControl("Table1").Controls)
{
if (x is RadNumericTextBox)
{
//how to get the data??????/
}
}
}
(thanks to those that actually read the whole post)
-----------------updated solution--------------------------------------------
I decided to change it and store the list from the db at page_load. With the list stored i loop through the list and use FindControl() to access the textboxes. Something like this..
//a couple containers
protected class ItemVal
{
public int Value { get; set; }
public string Name { get; set; }
}
protected List<ItemVal> items = new List<ItemVal>();
//get the list from that database
protected void GetItems()
{
foreach (var x in MyClass.GetItems())
{
ItemVal i = new ItemVal();
i.Name = x;
items.Add(i);
}
}
//submit
protected void submit_Click(object sender, EventArgs e)
{
foreach (var x in items)
{
RadNumericTextBox rntb = FindControl(x.Name) as RadNumericTextBox;
x.Value = (int)rntb.Value;
}
}
You need to cast x to a RadNumericTextBox and then pull out the property values you want, like this:
RadNumericTextBox theRadNumericTextBox = x as RadNumericTextBox;
string val = theRadNumericTextBox.Text;
Then for the other controls you want, you will need to put if conditions for their types, like this:
if (x is Label)
{
Label theLabel = x as Label;
string valLabel = theLabel.Text;
}
Here is the full code for the method:
protected void submit_Click(object sender, EventArgs e)
{
foreach (Control x in FindControl("Panel1").FindControl("Table1").Controls)
{
Label theLabel;
RadNumericTextBox theRadNumericTextBox;
if (x is RadNumericTextBox)
{
RadNumericTextBox theRadNumericTextBox = x as RadNumericTextBox;
string val = theRadNumericTextBox.Text;
}
if (x is Label)
{
Label theLabel = x as Label;
string valLabel = theLabel.Text;
}
// Either store up in a list or save to the database on each loop; it is recommended to store a list and send all the changes at once for a database save, but that is your choice
}
}

C# reassigning array values(down one step ex 5-4) that are within an object during a event

Just learning C# (along with object and event programing) and the teacher didn't really show us how to get things done.
class Postion
{
private int[] x_coordinate = new int[100];
private int[] y_coordinate = new int[100];
private double[] speed = new double[100];
private int[] direction = new int[100];
const int MAX_SPEED = 50;
int counter = 0;
public Postion()
{
x_coordinate[counter] = 0;
y_coordinate[counter] = 0;
speed[counter] = 0;
direction[counter] = 0;
}
//get set methods
public int X
{
get
{
return x_coordinate[counter];
}
set
{
x_coordinate[counter] = value;
}
}
There is one more Class between them
The values are frist assigned by a button click.
Airplane newplane = new Airplane();
private void BtnCreate_Click(object sender, EventArgs e)
{
bool box = txtName.Text != "";
if (box == true)
newplane.Name = txtName.Text;
else { }
box = txtx.Text != "";
if (box == true)
newplane.PlanePostion.X = int.Parse(txtx.Text);
else { }
Etc.
I can call on the array values for display for the list box.
private void lsbplanes_SelectedIndexChanged(object sender, EventArgs e)
{
placeholder = newplane.PlanePostion.Counter;
newplane.PlanePostion.Counter = lsbplanes.SelectedIndex;
if (newplane.PlanePostion.Counter < 0)
newplane.PlanePostion.Counter = 0;
else { }
lblxshow.Text = Convert.ToString(newplane.Getx());
but when using a destroy button to remove an item in the list box I need to have it so the box updates with the new values when the user selects the item in the listbox.
This is what I have to try and do it so far, it sets all the ones above to 0s but does remove the the deleted one fine
private void BtnKill_Click(object sender, EventArgs e)
{
if (lsbplanes.SelectedIndex == -1)
{
MessageBox.Show("Please select an item first.", "No item selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
placeholder = lsbplanes.SelectedIndex;
newplane.PlanePostion.Counter = lsbplanes.Items.Count;
while (newplane.PlanePostion.Counter > placeholder)
{
placex = newplane.PlanePostion.X;
placey = newplane.PlanePostion.Y;
placespeed = newplane.Getspeed();
placedic = newplane.Getdirection();
newplane.PlanePostion.Counter--;
newplane.PlanePostion.X = placex;
newplane.PlanePostion.Y = placey;
newplane.PlanePostion.Speed = placespeed;
newplane.PlanePostion.Direction = placedic;
}
lsbplanes.Items.RemoveAt(lsbplanes.SelectedIndex);
newplane.PlanePostion.Counter = lsbplanes.Items.Count;
}
anyone can help me on this?
I was torn in this question, answer exactly what your problem is, or suggest that you redesign it.
#Marc is right you should be using some sort of List<Position> on your Plane object (or a ReadOnlyObservableCollection<Position>).
#Marc is also right, that the problem you are having is that you are trying to push the values down from the end of the list and overwriting them. In these cases it is better to start from the deletion point and pull them down.
So if you have {1,2,3,4,5,6,7,8,9,10} and you delete from item 5, you would have {1,2,3,4,10,10,10,10,10,10}. The code below will let you end up with {1,2,3,4,6,7,8,9,0}
placeholder = lsbplanes.SelectedIndex;
int idx = placeholder;
while (idx < lsbplanes.Items.Count)
{
newplane.PlanePosition.Counter = idx+1;
placex = newplane.PlanePostion.X;
placey = newplane.PlanePostion.Y;
placespeed = newplane.Getspeed();
placedic = newplane.Getdirection();
newplane.PlanePostion.Counter = idx;
newplane.PlanePostion.X = placex;
newplane.PlanePostion.Y = placey;
newplane.PlanePostion.Speed = placespeed;
newplane.PlanePostion.Direction = placedic;
idx++;
}
// Need to zero out elements at the end
newplant.PlanePosition.Counter = lsbplanes.Items.Count;
/* Zeroing code goes here */
newplane.PlanePosition.Counter = placeholder;
lsbplanes.Items.RemoveAt(lsbplanes.SelectedIndex);

Categories

Resources