Hello Fellow C# and Windows phone developers,
For my windows phone application, I have a textfield requiring the user to enter their age. During debugging mode I entered the number .8. and clicked proceed and the application unexpectedly closed. What code do I need to add so I can post a message box informing the user that numbers with more than 1 decimal point is unacceptable. Please Help
Assuming the input is a string, try:
if (input.IndexOf('.') == -1 || input.LastIndexOf('.') == input.IndexOf('.'))
{
//good
}
else
MessageBox.Show("More than one decimal point");
A better way though would be to use TryParse which will check the number for formatting
float age;
if (float.TryParse(input, out age))
{
//good
}
else
MessageBox.Show("Invalid age.");
one way would be to limit the number of decimal place input to just one decimal place when user is entering their input.
this would be much better as it is real time instead of checking it at the end.
private void tbx_KeyDown(object sender, KeyEventArgs e)
{
//mark the sneder as a textbox control so we can access its properties
TextBox textBoxControl = (TextBox)sender;
//if there is already a decimals, do not allow another
if (textBoxControl.Text.Contains(".") && e.PlatformKeyCode == 190)
{
e.Handled = true;
}
}
Related
I am currently working on a custom control that allow users to enter either a decimal or in time format (hh:mm). So I would like that if the TextBox contain a period(.), the user will no longer add/enter a colon(:) and vice versa.
I have this code below so that user can only enter numeric, a period and a colon.
private void txtTime_KeyPress(object sender, KeyPressEventArgs e)
{
if ((!char.IsControl(e.KeyChar) & !char.IsDigit(e.KeyChar) & !(Convert.ToString(e.KeyChar) == ".") & !(Convert.ToString(e.KeyChar) == ":")))
{
e.Handled = true;
}
else
{
//only allow one '.' & ':'
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
else if (e.KeyChar == ':' && (sender as TextBox).Text.IndexOf(':') > -1)
{
e.Handled = true;
}
}
}
So my question is, how will I do it?
Can somebody help me? Thanks in advance.
For operators it is a nuisance if they have typed something, and they want to correct it, but they can't because there is an incorrect dot or a semicolon in it.
Suppose the operator tried to type 14:38:21, but instead types:
14.38
"Oh no, this is wrong, I wanted 14.38:21! So let's first continue typing :21 and then go back to change the dot into a colon!"
Imagine the operator's frustration when he can't type :21, and doesn't understand why
In windows forms, only validate entered input when the operator expresses he finished editing the input.
Therefore, use TextBox.OnValidating. When this one is called, you can either accept or decline the input and tell the operator what is wrong.
protected override void OnValidating (CancelEventArgs e)
{
e.Cancel = this.IsInputErrorDetected;
if (e.Cancel)
{
this.DisplayInputProblem();
}
}
Bonus point: also works with copy-paste.
I am not sure, if I understand your question good.
Maybe you are looking for maskedTextBox where you can specify mask of user input.
This one has mask for short time HH:MM
I need some help because I can't seem to get to display the text label here. I am using Windows Form C# VS 2015. When I press enter the error is on barangay = int.Parse(lblDistrict.Text); uhm also, I am applying the same way console.readline is used but it seems that it doesn't work. Can somebody help me in the code? :) Thanks in advance
private void txtBarangay_KeyPress(object sender, KeyPressEventArgs e)
{
int barangay = 0;
barangay = int.Parse(lblDistrict.Text);
if (e.KeyChar == (char)13)
{
if (barangay >= 1 && barangay <= 146)
{
lblDistrict.Text = "District 1";
}
else if (barangay >= 147 && barangay <= 267)
{
lblDistrict.Text = "District 2";
}
}
}
It is the matter of focus. When you press the key, which control is focused? Is it the one that you have written the KeyPress event for?
So you must make sure that either when the key is pressed either that specific control has the focus, or add this even to all controls.
I don't know what kind of Exception you get , but you must use Int.TryParse instead of int.parse .
check this link http://dailydotnettips.com/2016/01/16/back-to-basic-difference-between-int-parse-and-int-tryparse/
Thanks
First, Please include try-catch block in your program in-order to catch the exception.
If the string in the textBox contains anything other than ONLY numbers (Example "12er"), It will throw Exception. Try Int.TryParse if this is the case
In my program, I have texboxes which I type the grade of a student. But I want to restrict the user to not digit a number in format like 010 or 020. Also, if the user digits 1 and change to another textbox it autommaticaly changes this digited number (1) to 1,0.
I tried this, but when it enters the second condition, it gives me an error.
private void txt3Bimestre_Validated(object sender, EventArgs e)
{
if (txt3Bimestre.Text[0].ToString().Equals("1") ||
txt3Bimestre.Text[0].ToString().Equals("2") ||
txt3Bimestre.Text[0].ToString().Equals("3") ||
txt3Bimestre.Text[0].ToString().Equals("4") ||
txt3Bimestre.Text[0].ToString().Equals("5") ||
txt3Bimestre.Text[0].ToString().Equals("6") ||
txt3Bimestre.Text[0].ToString().Equals("7") ||
txt3Bimestre.Text[0].ToString().Equals("8") ||
txt3Bimestre.Text[0].ToString().Equals("9"))
{
if (txt3Bimestre.Text[1].ToString().Equals(",") || txt3Bimestre.Text.Substring(0, 2) == "10")
{
}
}
else
{
MessageBox.Show("Formato Inválido", "Alertaa", MessageBoxButtons.OK, MessageBoxIcon.Error);
txt3Bimestre.Clear();
txt3Bimestre.Focus();
}
}
The problem here is that you're trying to force user to not input data as he/she wants on the textbox.
What I recommend u to to is to let user enter what he/she wants and, after leave the textbox or execute another event, test the data if it's the valid format or show the user an alert about his/her "mistake".
For example:
double value;
bool ok = double.TryParse(txt3Bimestre.Text, out value))
if (ok)
{
txt3Bimestre.Text = value.ToString("0.00");
}
else
{
MessageBox.Show("Formato Inválido", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Error);
txt3Bimestre.Clear();
txt3Bimestre.Focus();
}
If you have problems with , or . for decimals (culture related differences for decimals separator), look for CultureInfo.InvariantCulture.
Hope it helps.
I have a simple form that takes 9 decimal numbers from 9 textboxes and I put some validation so that the users can only enter decimal numbers and nothing else.
Now the challenge I'm having is how to set the cursor in the textbox that had no decimal number after showing the error message in the try-catch statement?
Here's my code:
private void btn_Aceptar_Click(object sender, EventArgs e)
{
POI GPI = new POI();
POI VIM = new POI();
POI ST = new POI();
try
{
GPI.POI_x = Convert.ToDecimal(txt_GPIx.Text);
GPI.POI_y = Convert.ToDecimal(txt_GPIy.Text);
GPI.POI_z = Convert.ToDecimal(txt_GPIz.Text);
VIM.POI_x = Convert.ToDecimal(txt_VIMx.Text);
VIM.POI_y = Convert.ToDecimal(txt_VIMy.Text);
VIM.POI_z = Convert.ToDecimal(txt_VIMz.Text);
ST.POI_x = Convert.ToDecimal(txt_STx.Text);
ST.POI_y = Convert.ToDecimal(txt_STy.Text);
ST.POI_z = Convert.ToDecimal(txt_STz.Text);
}
catch (Exception)
{
MessageBox.Show("Ingrese solamente números en las variables GPI/VIM/ST", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//Set the cursor in the first textbox that had no decimals..
return;
}
Comisurales Comisurales = new Comisurales();
Comisurales.calculo_coord_comisurales(PC, AC, IHP, GPI, VIM, ST);
}
Let me add that I also have a function to ensure the user is only limited to enter decimals but I wasn't able to figure how to avoid the "." only or this for example: "1."
As an addition to my question, here's what gets validated every time the user press a key in the textbox:
private void ValidarDecimal(object sender, KeyPressEventArgs e)
{
// permitir 0-9, backspace, y decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
// chequear solamente un decimal
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}
I guess I have 2 ways to resolve my issue. Number one would be find a way to ensure the user never ever enters something weird in the textbox (which I've done partially) and number 2 would be to use the try-catch with the current limitations I mentioned above and then point the user to the textbox that has issues, both are acceptable.
The Decimal class has a TryParse method that could be used to avoid all this logic driven by catching exceptions (a very expensive approach in terms of performance)
decimal value;
if(decimal.TryParse(txt_GPIx.Text, out value))
GPI.POI_x = value;
else
{
MessageBox.Show("Invalid decimal value");
txt_GPIx.Focus();
}
Of course this code needs to be repeated for every control in your list, but you could write a generic function like this one
private decimal GetValueAndValidate(Textbox txt, out bool isOK)
{
isOK = true;
decimal value = 0m;
if(!decimal.TryParse(txt.Text, out value))
{
MessageBox.Show("Invalid decimal value");
txt.Focus();
isOK = false;
}
return value;
}
and then use the following approach in your code inside the button click
bool isOK = true;
if(isOK) GPI.POI_x = GetValueAndValidate(txt_GPIx, out isOK);
if(isOK) GPI.POI_y = GetValueAndValidate(txt_GPIy, out isOK);
.... and so on for the other fields ....
For the second part of your question, finding a way to completely control the input logic is not easy. What happens for example if your user PASTE an invalid text in your textbox? There are very edge case situations that takes a lot of effort to code correctly. It is a lot more easy to leave freedom of typing to your user and apply a strict logic when you get that input.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# GUI application that stores an array and displays the highest and lowest numbers by clicking a button
This is updated from 13 hours ago as I have been researching and experimenting with this for a few. I'm new to this programming arena so I'll be short, I'm teaching myself C# and I'm trying to learn how to have integers from a user's input into a textbox get calculated from a button1_Click to appear on the form. Yes, this is a class assignment but I think I have a good handle on some of this but not all of it; that's why I'm turning to you guys. Thanks for all of the advice guys.
I'm using Microsoft Visual Studio 2010 in C# language. I'm using Windows Forms Application and I need to create a GUI that allows a user to enter in 10 integer values that will be stored in an array called from a button_Click object. These values will display the highest and lowest values that the user inputted. The only thing is that the array must be declared above the Click() method.
This is what I have come up with so far:
namespace SmallAndLargeGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void inputText_TextChanged(object sender, EventArgs e)
{
this.Text = inputText.Text;
}
public void submitButton_Click(object sender, EventArgs e)
{
int userValue;
if(int.TryParse(inputText.Text, out userValue))
{
}
else
{
MessageBox.Show("Please enter a valid integer into the text box.");
}
int x;
x = Convert.x.ToString();
int squaredResults = squared(x);
int cubedResults = cubed(x); squared(x);
squaredLabel.Text = x.ToString() + " squared is " + squaredResults.ToString();
cubedLabel.Text = x.ToString() + " cubed is " + cubedResults.ToString();
}
public static int squared(int x)
{
x = x * x;
return x;
}
public static int cubed(int x)
{
x = x * squared(x);
return x;
}
}
}
Now I can't run this program because line 38 shows an error message of: 'System.Convert' does not contain a definition for 'x' Also I still have to have an array that holds 10 integers from a textbox and is declared above the Click() method. Please guys, any help for me? This was due yesterday.
As a couple of comments have mentioned, there really isn't enough information here to provide you with a useful answer. There are two main User Interface frameworks in .Net for windows applications. One of these is commonly referred to as "WinForms" and the other is "WPF" or "Windows Presentation Foundation."
I'm going to go with you are most likely using WinForms as it is the older of the two technologies. The approach here can be used on both sides with a little tweaking. Setting text in a text box is very similar to setting text programaticly on a label. You can get more detail on that on MSDN: How to: Display Text on a Windows Form; How to: Use TextBox Controls to Get User Input.
If you are using WPF the "back end" code is pretty much the same. You just need to make sure your textbox has an x:Name="userInputTextBox" so you can reference it in your code behind. Be mindful that your users can input "1", "3" or "abcd" in the field. Ensuring your app doesn't bomb is most likely outside of the assignment but feel free to look up C# int.TryParse(...) and "Try Catch" :-)
Your button handler could look like this:
void btnUserClick_Click(object sender, System.EventArgs e)
{
int userValue;
if(int.TryParse(txtUserInput.Text, out userValue))
{
// We have the value successfully, do calculation
}
else
{
// We don't have the users value.
MessageBox.Show("Please enter a valid integer into the text box.")
}
}
In your retrieveInput_Click handler you are assigning the min/max numbers to a local int. Once you determine your min/max numbers in the logic, you will need to assign those local integers to a UI element for display.
Since we don't have any details on your specific UI choices, one simple solution could be to add 2 labels to your form, and then in the code you would place the result in the label:
for (int i = 0; i < numbers.Length; ++i)
{
if (numbers[i] < min)
min = numbers[i];
if (numbers[i] > max)
max = numbers[i];
}
// Assign Minimum to Label1
Label1.Text = "Minimum Value: " + min.ToString();
// Assign Maximum to Label2
Label2.Text = "Maximum Value: " + max.ToString();
define the textbox named textbox1 or txt_name
you can write the button1_Click function :
int i_value = Convert.ToInt16(txt_name.Text);
ok. I haven't try catch the exceptions.... :(
maybe above answer is right.
btw, i think this question mainly focus on how to get int type from text box. right?