C# - Copy input from one textbox to another and vise versa - c#

this is my first post and I'm fairly new to C#
I'm trying to create a Celsius to Fahrenheit converter and vise versa.
I have two textboxes, the user can either input a number into the Celsius textbox and the Fahrenheit will automatically be calculated and displayed into the Fahrenheit textbox or the user can input into the Fahrenheit and the Celsius value will be calculated and output.
Here is the code I have so far, this is a WFA.
private void txtCelsius_TextChanged(object sender, EventArgs e)
{
///*
if(string.IsNullOrEmpty(txtCelsius.Text))
{
txtFahrenheit.Clear();
return;
}
txtFahrenheit.Text = ((double.Parse(txtCelsius.Text)) * 1.8 + 32).ToString();
//*/
}
private void txtFahrenheit_TextChanged_1(object sender, EventArgs e)
{
///*
if (string.IsNullOrEmpty(txtFahrenheit.Text))
{
txtCelsius.Clear();
return;
}
txtCelsius.Text = ((double.Parse(txtFahrenheit.Text)) / 1.8 - 32).ToString();
//*/
}
Clearly, when I run this and input a value into either one of the textbox it will create an infinite loop. If I comment one or the other out it works for the other one.
Can someone help? Is there a way I can do something like the following pseudocode.
if textbox1 is getting input
textbox2.input = disabled
do calculations and display
if textbox2 is getting input
textbox1.input = disabled
do calculations and display
If tried searching for a solution but finding it hard to word what I'm looking for and coming up with no solutions.
PS. I keep seeing this in other posts, this is not homework, I'm just trying to come up with small programs to learn.

You are getting into an infinite loop because each time you update the other text boxes value it's firing the TextChanged event. To handle this add a variable to control when to update use TextChanged code.
bool _updating = false;
private void txtCelsius_TextChanged(object sender, EventArgs e)
{
if (!_updating)
{
try
{
_updating = true;
///*
if(string.IsNullOrEmpty(txtCelsius.Text))
{
txtFahrenheit.Clear();
return;
}
txtFahrenheit.Text = ((double.Parse(txtCelsius.Text)) * 1.8 + 32).ToString();
//*/
}
finally
{
_updating = false;
}
}
}
private void txtFahrenheit_TextChanged_1(object sender, EventArgs e)
{
if (!_updating)
{
try
{
_updating = true;
///*
if (string.IsNullOrEmpty(txtFahrenheit.Text))
{
txtCelsius.Clear();
return;
}
txtCelsius.Text = ((double.Parse(txtFahrenheit.Text)) / 1.8 - 32).ToString();
//*/
}
finally
{
_updating = false;
}
}
}

Related

Windows Form. Limit User input to a certain range

I am creating a windows form program for class and I am trying to limit input for a 'weight' textbox from 1-1000. I got the user input to parse to a double but some reason the error message I created will not popup at the right time as intended. (The error message will popup only if I enter digits passed 5 digits... so I can enter 2222 or 10000 without an error)
private void Weight_KeyPress(object sender, KeyPressEventArgs e)
{
var sourceValue = Weight.Text;
double doubleValue;
if (double.TryParse(sourceValue, out doubleValue))
{
if (doubleValue > 1000 )
{
MessageBox.Show("Cannot be greater than 1000");
}
}
}
instead of using KeyPress you should use TextChanged event
because if you use keypress the new char is not part of the control text yet.
private void inputTextBox_TextChanged(object sender, EventArgs e)
{
var inputTextBox = sender as TextBox;
var sourceValue = inputTextBox.Text;
double doubleValue;
if (double.TryParse(sourceValue, out doubleValue))
{
if (doubleValue > 1000)
{
MessageBox.Show("Cannot be greater than 1000");
}
}
}

C# - refresh textbox while typing value

How can i make auto refresh textbox while typing value like this?
i tried to do the same but it did not work. i always to hit ENTER to refresh or click on up/down arrows to refresh the value
here is the code
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
try
{
double a = double.Parse(s1.Text); //textbox 1
double b = double.Parse(s2.Text); //textbox 2
double s = a * b;
resultSpeed.Text = "" + s; //s is the result
}
catch
{
MessageBox.Show("Please input the number");
}
}
Just use event KeyUp. It will trigger every time you put a symbol.
ValueChanged isn't working because it only triggers when you are done with editing - you press enter or change focus.
So basically change your event from ValueChanged to KeyUp.
I'm not posting any code because the only change will be subcribing to other event. Your function is fine, however you should change its name :)
Put your code into textbox's TextChanged Event.
Like this
private void textBox1_TextChanged(object sender, EventArgs e)
{
calculate();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
calculate();
}
private void calculate()
{
double a = 0, b = 0, demo;
if (double.TryParse(textBox1.Text, out demo))
a = double.Parse(textBox1.Text); //textbox 1
if (double.TryParse(textBox2.Text, out demo))
b = double.Parse(textBox2.Text); //textbox 2
double s = a * b;
textBox3.Text = s.ToString(); //s is the result
}

Calculation is wrong

What should happen
My exexcrise is it to prgramm a calculator which is able to do calculations in 'queue'.
Example:
User enters first number in txtZahl and then clicks one of the button. The needed calculation should be saved in the list numbers and txtZahl should be cleared. The user can now enter a new number and press a button etc.
When the user clicks on btnEqu the foreach should take every calculation from the list and do the calculation. If this is done the result should be displayed in txtZahl.
Problem
The calculations are not correct. For example I get 0.00 as result for 4-3.
I know that the idea with the extra class is not the best way, but I would like to keep it, to see what my teacher thinks about it.
Thank you for helping!
Code:
Form1.cs
double ergebniss = 0;
Boolean firstRun = true;
List<Rechnung> numbers = new List<Rechnung>();
Rechnung.RechenArt lastArt;
private void btnMinus_Click(object sender, EventArgs e)
{
if (isValid())
{
if (firstRun)
{
ergebniss = Convert.ToDouble(txtZahl.Text);
}
numbers.Add(new Rechnung(Convert.ToDouble(txtZahl.Text), Rechnung.RechenArt.Subtraktion));
lastArt = Rechnung.RechenArt.Subtraktion;
clearAndFocus();
}
}
private void btnEqu_Click(object sender, EventArgs e)
{
foreach (Rechnung r in numbers)
{
switch (r.getArt())
{
case Rechnung.RechenArt.Subtraktion:
{
ergebniss -= r.getNumber();
break;
}
}
}
txtZahl.Text = ergebniss.ToString("f2");
}
}
if (firstRun)
{
ergebniss = Convert.ToDouble(txtZahl.Text);
firstRun = false;
return;
}
first you forgot to
firstRun = false; after that
then I advice you to display just clean string
txtZahl.Text = ergebniss.ToString();
you also doesn't use lastArt variable don't know if that's necessary.

Event located immediately after DataSource Update from ActiveEditor in Grid

What I need to do is calculated the value of one field in the grid, based on the values of other fields in the grid. I need to run this calculation After the value in one of the dependent cells is changed, but only if the value was a Valid entry. The EditValueChanged, Validating, and Validated events of the editor/repository all occur before the data is posted back into the datasource. I am wondering if there is any event I can hook into that will allow me to fire this calculation after the data has been post back into the datasource, but before control is returned to the user.
Sample Code
//calculation functions
private void SetCalcROP(MyObjectt Row)
{
//rop = m/hr
TimeSpan ts = Row.ToTime - Row.FromTime;
double diffDepth = Row.EndDepth - Row.StartDepth;
if (ts.TotalHours > 0)//donot divide by 0
Row.ROP = diffDepth / ts.TotalHours;
else
Row.ROP = 0;
}
private void SetCalcDeltaP(MyObject Row)
{
Row.DeltaPress = Row.SPPOnBtm - Row.SPPOffBtm;
}
//events
private void repNumberInput_Validated(object sender, EventArgs e) //is actaully ActiveEditor_Validated
{
if (vwDDJournal.FocusedColumn.Equals(colSPPOff) || vwDDJournal.FocusedColumn.Equals(colSPPOn))
SetCalcDeltaP(vwDDJournal.GetFocusedRow() as MyObject);
}
private void repNumberInput_NoNulls_Validated(object sender, EventArgs e) //is actaully ActiveEditor_Validated
{
if (vwDDJournal.FocusedColumn.Equals(colStartDepth) || vwDDJournal.FocusedColumn.Equals(colEndDepth))
SetCalcROP(vwDDJournal.GetFocusedRow() as MyObject);
}
private void repTimeEdit_Validated(object sender, EventArgs e) //is actaully ActiveEditor_Validated
{
SetCalcROP(vwDDJournal.GetFocusedRow() as MyObject);
}
private void repNumberInput_NoNulls_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
TextEdit TE = sender as TextEdit;
//null is not valid for this entry;
if (string.IsNullOrEmpty(TE.Text))
{
e.Cancel = true;
vwDDJournal.SetColumnError(vwDDJournal.FocusedColumn, "This Column may not be blank");
return;
}
else
{
double tmp;
if (!Double.TryParse(TE.Text, out tmp))
{
e.Cancel = true;
vwDDJournal.SetColumnError(vwDDJournal.FocusedColumn, "This Column must contain a number");
return;
}
}
}
private void repNumberInput_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
TextEdit TE = sender as TextEdit;
//null is not valid for this entry;
if (!string.IsNullOrEmpty(TE.Text))
{
double tmp;
if (!Double.TryParse(TE.Text, out tmp))
{
e.Cancel = true;
vwDDJournal.SetColumnError(vwDDJournal.FocusedColumn, "This Column must contain a number");
return;
}
}
}
private void repTimeEdit_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
if (vwDDJournal.FocusedColumn.Equals(colToTime))
{//dont bother to check from time
//TIME TRAVEL CHECK!!!!
DateTime FromTime = Convert.ToDateTime(vwDDJournal.GetRowCellValue(vwDDJournal.FocusedRowHandle, colFromTime));
TimeEdit te = sender as TimeEdit;
DateTime ToTime = Convert.ToDateTime(te.EditValue);
if (ToTime < FromTime)
{//TIME TRAVEL
e.Cancel = true;
vwDDJournal.SetColumnError(vwDDJournal.FocusedColumn, "To Time must be greater than From Time");
return;
}
}
}
the problem is that everywhere I call this from, and whether I use vwDDJournal.GetRowCellValue(...) or vwDDJournal.GetFocusedRow() as MyObject, I still get the old edit value.
Requirements
I have to have the input validated before running the calculation.
I have to run the calculation immediately after making the change.
... What I need to do is calculated the value of one field in the grid, based on the values of other fields in the grid.
The best way to accomplish this task is using Unbound Columns feature.
The following example demonstrates how to implement this feature by handling the ColumnView.CustomUnboundColumnData event:
// Provides data for the Total column.
void gridView1_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e) {
if (e.Column.FieldName == "Total" && e.IsGetData) e.Value =
getTotalValue(e.ListSourceRowIndex);
}
// Returns the total amount for a specific row.
decimal getTotalValue(int listSourceRowIndex) {
DataRow row = nwindDataSet.Tables["Order Details"].Rows[listSourceRowIndex];
decimal unitPrice = Convert.ToDecimal(row["UnitPrice"]);
decimal quantity = Convert.ToDecimal(row["Quantity"]);
decimal discount = Convert.ToDecimal(row["Discount"]);
return unitPrice * quantity * (1 - discount);
}
Original example: How to: Add an Unbound Column Storing Arbitrary Data
You can also implement calculated value for unbound column using expressions:
GridColumn columnTotal = new GridColumn();
columnTotal.FieldName = "Total";
columnTotal.Caption = "Total";
columnTotal.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
columnTotal.UnboundExpression = "[Quantity] * [UnitPrice] * (1 - [Discount])";
gridView1.Columns.Add(columnTotal);
How about CustomCellValue?
After posting back to the data source refresh the data.
It's called whenever data is updated or view is changed.

Cancel/Clear button event Post Back And Trying To Validate Fields

this is driving me crazy.
I have a piece of code on a Windows Form Control, this code ensures the form clears and put the focus back to the first Control (Phone Number). The problem is I am using On-Leave Event Handles and this handler contain the Validation code so that the Phone is validated when the use leaves the control.
When I hit Reset or Exit of the form, it not only clears the form, it also sends the focus back to the Phone field, causing the control (Textbox) to Validate.
I need the focus on the Phone control with at the validation on focus, is there a way I can prevent this behavior?
private void txtPhone_Leave(object sender, EventArgs e)
{
Int64 ConvertPhone;
if (txtPhone.Text.Trim().Length != 10)
{
lblPhoneError.Visible = true;
lblErrorIndicator.Visible = true;
lblErrorIndicator.Text = "*Valid 10 digit phone number required";
}
else if (Int64.TryParse(txtPhone.Text, out ConvertPhone))
{
lblPhoneError.Visible = false;
lblErrorIndicator.Visible = false;
txtPhone.MaxLength = 10;
txtPhone.Text = txtPhone.Text.Substring(0, 3) + "." + txtPhone.Text.Substring(3, 3) + "." + txtPhone.Text.Substring(6, 4);
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txtPhone.Clear();
txtPhone.Focus();
}
private void txtPhone_Enter(object sender, EventArgs e)
{
txtPhone.Text = txtPhone.Text.Replace(".", "");
}
Thanks everyone!
if (txtPhone.Text.Trim().Length != 10)
{
if (txtPhone.Text != "")
{
lblErrorIndicator.Visible = true;
lblErrorIndicator.Text = "*Valid 10 digit phone number required";
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txtPhone.Clear();
lblErrorIndicator.Text="";
txtPhone.Focus();
}
I can understand your problem but tell me what you want to do at the end?

Categories