My code is reading the textbox just once - c#

The problem is that my code is just reading the Textboxes just the very first time, wheneaver I do any change to the Textboxes it doesn`t read the new ones.
This is the code of the form with 2 textBoxes.
public partial class Form1 : Form
{
double tb1, tb2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 forming = new Form1();
Reading objR = new Reading(forming);
tb1 = double.Parse(textBox1.Text);
tb2 = double.Parse(textBox2.Text);
textBox4.Text= objR.mAdd(tb1,tb2).ToString();
textBox5.Text = objR.mAdd2().ToString();
}
}
And the class where I´m trying to read the textboxes is this:
class Reading
{
double _tb1, _tb2;
public Reading(Form1 form)
{
this._tb1 = double.Parse(form.textBox1.Text);
this._tb2 = double.Parse(form.textBox2.Text);
}
public double mAdd(double a, double b)
{
return a + b;
}
public double mAdd2()
{
return _tb1 + _tb2;
}
}
I think that Reading objR = new Reading(forming);reads the TextBoxes but they are read just once, When I Click my Button again it is just giving me the same info, I added the method mAdd to make sure the textboxes are being used correctly.
What can I do to actualy read the newest data in the Textboxes?

First, it's overkill to pass the entire form in to your Reading class' constructor. Why not just have a constructor with two double arguments?
Second, if you have to pass the form, then remove the Form1 forming = new Form1(); and replace the next line with Reading objR = new Reading(this);

The main reason is you are passing a NEW instance of Form1 to your reading class and not the instance where the textboxes you are changing.
Just to add to ffa's answer.
With this, the return value of reading class' mAdd and mAdd2 will be the same.
private void button1_Click(object sender, EventArgs e)
{
tb1 = double.Parse(textBox1.Text);
tb2 = double.Parse(textBox2.Text);
Reading objR = new Reading(tb1, tb2);
textBox4.Text= objR.mAdd(tb1,tb2).ToString();
textBox5.Text = objR.mAdd2().ToString();
}
class Reading
{
double _tb1, _tb2;
public Reading(string tb1, string tb2)
{
this._tb1 = double.Parse(tb1);
this._tb2 = double.Parse(tb2);
}
public double mAdd(double a, double b)
{
return a + b;
}
public double mAdd2()
{
return _tb1 + _tb2;
}
}

public partial class Form1 : Form
{
double tb1, tb2;
private void button1_Click(object sender, EventArgs e)
{
Reading objR = new Reading();
tb1 = double.Parse(textBox1.Text);
tb2 = double.Parse(textBox2.Text);
textBox4.Text= objR.mAdd(tb1,tb2).ToString();
textBox5.Text = objR.mAdd2().ToString();
}
public class Reading
{
public double Reading(double a,double b)
{
_tb1= a;
_tb2 = b;
}
public double mAdd(double a, double b)
{
return a + b;
}
public double mAdd2()
{
return _tb1 + _tb2;
}
}

Related

refresh after .showDialog and show items in list - c# .NET

Currently in my program a user opens form 1 to create a new instance of a class and it is then saved to a list. After form 1 closes I would like the main form to reload and show the updated list on the screen. I am having trouble figuring out how to refresh the main navigation and how I would get the list to show on the form.
MainNaviagation
public partial class MainNavigation : Form
{
private Model m_modelObj;
public MainNavigation(Model modelObj)
{
InitializeComponent();
m_modelObj = modelObj;
m_modelObj.ChocolateAdded += m_modelObj_ChocolateAdded;
}
void m_modelObj_ChocolateAdded(Chocolate newChocolate)
{
//whole list of chocolates
List<Chocolate> chocolateList = m_modelObj.ChocolateList;
}
private void button1_Click(object sender, EventArgs e)
{
string candy = comboBox1.SelectedItem.ToString();
Form1 aForm1 = new Form1(textBox1.Text, candy, m_modelObj);
aForm1.ShowDialog();
}
}
Model Class:
{
public delegate void ChocolateAddedEventHander(Chocolate newChocolate);
public class Model
{
public event ChocolateAddedEventHander ChocolateAdded;
public List<Chocolate> ChocolateList = new List<Chocolate>();
public void AddChocolateInList(Chocolate chocolate)
{
ChocolateList.Add(chocolate);
if (ChocolateAdded != null)
ChocolateAdded(chocolate);
}
}
form1
public partial class Form1 : Form
{
Model m_model;
public Form1(string name, string candy, Model modelObj)
{
InitializeComponent();
m_model = modelObj;
string str = name + " selected : ";
label1.Text = str;
}
private void button1_Click(object sender, EventArgs e)
{
Chocolate newChocolate = new Chocolate(comboBoxChocolateSelection.SelectedItem.ToString(), 12.5, true, 2);
m_model.AddChocolateInList(newChocolate);
this.Close();
}
}
chocolates
public class Chocolate
{
#region Fields
public string flavor;
public double cost;
public bool giftWrap;
public int quantity;
#endregion End of Fields
#region Constructors
public Chocolate(string flavor, double cost, bool giftWrap, int quantity)
{
this.flavor = flavor;
this.cost = cost;
this.giftWrap = giftWrap;
this.quantity = quantity;
}
#endregion End of Constructors
}

Data from form1 listbox to form2 textbox

The goal of the program assignment I'm working on requires me to fill a listbox with items taken from a data file, and then allowing the user to modify parts of the selected item. To do this, I need assistance in figuring out how to pass part of a listbox's selected item in one form to a textbox in another form.
Here's the coding I have for the first form in my program:
public partial class Form1 : Form
{
const char DELIM = '\\';
const string FILENAME = #"C:\Visual Studio 2015\Data Files\Training Workshops data";
string recordIn;
string[] Fields;
static FileStream file = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(file);
public int X;
public Form1()
{
InitializeComponent();
}
public class Workshop
{
public string title { get; set; }
public int days { get; set; }
public string categrory { get; set; }
public double cost { get; set; }
public string[] categrorynames =
{
"Application Development",
"Databases",
"Networking",
"System Administration"
};
}
Workshop shop = new Workshop();
private void button1_Click(object sender, EventArgs e)
{
Form2 secondForm = new Form2();
secondForm.Show();
}
private void PopulateList(string filePath)
{
while(recordIn != null)
{
try
{
recordIn = reader.ReadLine();
Fields = recordIn.Split(DELIM);
X = Convert.ToInt32(Fields[0]);
shop.categrory = shop.categrorynames[X];
shop.days = Convert.ToInt32(Fields[1]);
shop.title = Fields[3];
shop.cost = Convert.ToDouble(Fields[2]);
}
catch (Exception A)
{
if (X < 0 && X > 3)
{
shop.categrory = "invalid";
}
if (shop.days != Convert.ToInt32(Fields[1]))
{
shop.days = 0;
}
if (shop.title != Fields[3])
{
shop.title = "invalid";
}
if (shop.cost != Convert.ToDouble(Fields[2]))
{
shop.cost = 0;
}
}
}
}
}
And below is a link to a screenshot of the second form:
http://i.stack.imgur.com/IRqVh.png
I need to transfer the shop.categrory data of form1's listbox's selected item to the second form's, and the shop.title, shop.days and shop.cost to the corresponding textbox's. From there I can make it so that whatever the user enters in the textboxes would change the data of the selected item when they press the "save and exit" button.
Any help would be appreciated, and if anyone notices an error in the coding I have now, please feel free to point them out.
Create a Parameterized constructor in form2 that accepts a String, and create it's instance in first form, and pass the value you want to pass to the second form:
private void button1_Click(object sender, EventArgs e)
{
Form2 secondForm = new Form2("DATA TO BE SENT");
secondForm.Show();
}
and in form2 Create a Constructor:
public Form2(string data)
{
InitializeComponent();
txtData.Text=data;
}

How do I add calculations to my GUI in C#?

This is my first time using Windows Forms on Visual Studio with C#. I am trying to make my form have a button where when you click "Calculate Amount Due" that it will put what was calculated into the "Amount Due" field. But, anytime I say "textBox3 = aOrder.AmountDue()", it says it can not convert double to System.Windows.Forms.TextBox. How do I convert this appropriately? Here is my code for the program.
namespace MidTermPizzas
{
class pizzaOrder
{
public int numberOfCokes
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
public int numberOfPizzas
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
public double InputOrder()
{
const double COKE_PRICE = 1.49;
const double PIZZA_PRICE = 7.99;
double inputOrder = (numberOfCokes * COKE_PRICE) + (numberOfPizzas * PIZZA_PRICE);
return InputOrder();
}
public double TaxDue()
{
const double TAX = .073;
double taxDue = (this.InputOrder() * TAX);
return TaxDue();
}
public double GetAmountDue()
{
double getAmountDue = this.InputOrder() + this.TaxDue();
return GetAmountDue();
}
public double GetAmountPaid()
{
double getAmountPaid;
return GetAmountPaid();
}
public double GetChargeDue()
{
double getChargeDue = this.GetAmountDue() - this.GetAmountPaid();
return GetAmountPaid();
}
}
}
namespace MidTermPizzas
{
public partial class Form1 : Form
{
pizzaOrder aOrder = new pizzaOrder();
DailySummary aSummary = new DailySummary();
public Form1()
{
InitializeComponent();
}
//click File, Exit
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Enjoy your pizza!");
this.Close();
}
//click View, All Orders Placed
private void allOrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
AllOrdersPlaced myForm = new AllOrdersPlaced();
myForm.Show();
}
//click View, Summary of Orders Placed
private void summaryOfOrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
SummaryOfOrdersPlaced myForm2 = new SummaryOfOrdersPlaced();
myForm2.Show();
}
//text in box to the right of "Amount Due"
private void textBox3_TextChanged_1(object sender, EventArgs e)
{
textBox3 = aOrder.GetAmountDue();
}
}
}
textBox3.Text = Convert.ToString(aOrder.AmountDue());
Assuming AmountDue() is returning a Double.
You had two problems, you were trying to set the actual textbox object to a string instead of the .Text property of the textbox, and you aren't converting the double to a string.
textBox3 is the object. The object has various methods (to do stuff) and properties (to hold stuff), specifically textBox3.Text which is where you can set the text in the box. Remember MSDN is your friend.
To avoid this error, it's necessary assign the value Order.GetAmountDue() for Text property. This property contains the value of TextBox:
textBox3.Text = aOrder.GetAmountDue();
Because it's necessary keep the compatibility between the types, so you can't assign a Double for a TextBox, but you can assign a Double to a string (in this case the Text property its a string).
Maybe you need format the value, for more information see this link:
Double.ToString
In addition to the Textbox issue, I also don't think you should be returning the public method itself.ie
instead of
public double TaxDue()
{
const double TAX = .073;
double taxDue = (this.InputOrder() * TAX);
return TaxDue();
}
You should have
public double TaxDue()
{
const double TAX = .073;
double taxDue = (this.InputOrder() * TAX);
return taxDue;
}
The first implementation doesn't make sense.

User input in subform

I am trying to get values back from a form.
I have been trying this: How to return a value from a Form in C#?
It does not work for me, maybe I'm doing something wrong but at the second part.
using (var form = new frmImportContact())
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
string val = form.ReturnValue1; //ReturnValue1 is not an option...
string dateString = form.ReturnValue2;
//Do something here with these values
//for example
this.txtSomething.Text = val;
}
}
I am unable to get "ReturnValue1" to show up. It is declared public, what else do I need to do?
Here is what I have written. My sub-form:
namespace ASPE.GUI.SensorWizard
{
public partial class PortsSensitivity : Form
{
public int ReturnValue1 { get; set; }
public PortsSensitivity()
{
InitializeComponent();
}
private void PortsBox_ValueChanged(object sender, EventArgs e, KeyPressEventArgs m)
{
this.ReturnValue1 = Convert.ToInt16(PortsBox.Value);
}
private void PortsSensitivity_Load(object sender, EventArgs e)
{
}
}
}
And my main form:
//Show Form (Number of Ports, Sensitivity)
Form Part3 = new ASPE.GUI.SensorWizard.PortsSensitivity();
DialogResult dr3 = new DialogResult();
dr3 = Part3.ShowDialog();
//Write Variables
int numofports = Part3.ReturnValue1; //Not an option.
//Close Form
Your Part3 variable is defined as type Form which does not declare the ReturnValue1 property. (the ReturnValue1 property is declared on your PortSensitivity class).
Change
Form Part3 = new ASPE.GUI.SensorWizard.PortsSensitivity();
to
PortSensitivity Part3 = new ASPE.GUI.SensorWizard.PortsSensitivity();
Your first example is also instantiating something of type frmImportContact in the using statement but you have not shown the implementation of this. Check you have declared the property on this type (or that you aren't meant to be creating an instance of the PortSensitivity type).

Strange error (Input string is not in correct format.)

This is my code:
namespace Class_Properties {
public partial class Form1 : Form {
private string firstHeight1 = "";
public int firstHeight {
get {
return Convert.ToInt32( firstHeight1 );
}
}
public Form1() {
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e ) {
firstHeight1 = textBox2.Text;
Form2 secondForm = new Form2();
secondForm.Show();
}
}
}
and then the other class:
namespace Class_Properties {
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
Form1 mainWindow = new Form1();
this.Height = mainWindow.firstHeight;
}
}
}
When I run, I type 200 as value for textbox2 and click button1, then Visual Studio says the following exception:
What could I do to solve this error?
This is the failure:
InitializeComponent();
Form1 mainWindow = new Form1();
this.Height = mainWindow.firstHeight; //<--
No matter what you did on the other Form1, it won't show up in this one because it's a new instance so firstHeight == string.Empty and will fail the parse.
You'll have to send the existing Form1 to Form2:
public Form2(Form1 parent)
{
this.Height = parent.firstHeight;
}
// called like so from Form1:
var form2 = new Form2(this);
Though admittedly, it would be better to send only what you need:
public Form2(int desiredHeight)
{
this.Height = desiredHeight;
}
// called like so from Form1:
var form2 = new Form2(this.firstHeight);
What is the value of firstHeight1 when it throws the exception?
You may want to look at int.TryParse() instead:
int output = 0;
int.TryParse(firstHeight1, out output);
return output;
If it can't parse the value, it won't set output, instead of raising an exception.
More info on int.TryParse: http://msdn.microsoft.com/en-us/library/f02979c7.aspx
EDIT: The problem is you're re-instantiating Form1 and the value is never set in the new instance of Form1, from Form2. You should set a property in Form2 to that value.
class Form2
{
public int FirstHeight { get; set; }
}
...
Form2 form2 = new Form2();
form2.FirstHeight = this.FirstHeight;
form2.Show();
Since your firstHeight1 is String.Empty and no equivalent for empty string can be found in Int type. Hence the error..
In your Form2 instance, the value is still String.Empty. First set it to some value.
In Form2 when you say:
Form1 mainWindow = new Form1();
this.Height = mainWindow.firstHeight;
You aren't accessing the Form1 you had been using earlier, you're creating a brand new one with an empty textbox value.
What you should be doing is passing the height value into the second form when it is created:
public Form2(int height)
{
// use height here
}
and in button click:
Form2 secondForm = new Form2(firstHeight);
secondForm.Show();
You can do something like this.
public int? FirstHeight
{
get
{
int? returnValue = null;
int temp;
if (int.TryParse(textBox2.Text, out temp))
{
returnValue = temp;
}
return returnValue;
}
}
Then you just call the FirstHeight property when you need the value:
if (FirstHeight.HasValue)
{
// Access the int value like so:
int height = FirstHeight.Value;
}
If you don't want to use a Nullable type, you could do this instead:
public int FirstHeight
{
get
{
int returnValue; // Or some other default value you can check against.
if (!int.TryParse(textBox2.Text, out returnValue))
{
// If the call goes in here, the text from the input is not convertable to an int.
// returnValue should be set to 0 when int.TryParse fails.
}
return returnValue;
}
}
Your code looks like
public int FirstHeight
{
get
{
double Num;
bool isNum = double.TryParse(firstheight1, out Num);
if (isNum)
{
return firstheight1;
}
else
{
return 0; or
your message goes here
}
}
}

Categories

Resources