Windows Forms - customizing MaskedTextBox - c#

I need to use basic functionality of the MaskedTextBox. I can get use of the 5 digit mask but there are few things that I want to change. Right now the box is looking like this:
and there are two thing I don't like. First - the Prompt char which is undersoce _. I deleted the field value in order to leave it empty (as I would like it to appear) but this gives an error - The property value is invalid. So is there a way to get rid of these underscores? And second - I use this value for one of my entity properties which is of integer type so I make a convertion :
if (txtNumOfAreas.Text != "")
{
string temp = txtNumOfAreas.Text;
bool result = Int32.TryParse(temp, out convertValue);
if (result)
{
entity.AreasCnt = convertValue;
}
else
{
MessageBox.Show(Resources.ERROR_SAVE, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
else
{
entity.AreasCnt = null;
}
which works fine unless someone decides to make experiments and insert something like _1__5_ then the conversion fails, but at first place I would like to make possible to write the digits only one after another. So is this possible too?

It looks like your MaskedEdit is more trouble than it's worth to deal with your particular range of issues. A better control to use might be the NumericUpDown.
The upside to NumericUpDown:
There are no underscore prompts to try and get rid of
It will only accept numeric input
So there is no need to try and convert the value. You will always have an integer
Setting Minimum and Maximum value properties gives you automatic data entry validation
Provides multiple modes of data entry:
Typing
Clicking up/down buttons with a mouse
Up/down with keyboard
If you like, you could hide the up/down buttons altogether: C# WinForms numericUpDown control (removing the spin box)

So to get the _ to be a space you just need to set the mask character to a single space. And to resolve the conversion error, just set the AllowPromptAsInput property to false so that the user can't actually end up with something like your example.

Related

How to change user input in DataGridView cell from dot into a comma?

I would really appreciate your help.
I have a DataGridView where user will be giving us double (2,43 etc).
I want to write a function which can detect if user puts dot in place of comma and just change it itself or treat it as comma for the calculations.
If it was a console app I would just simply write something like
public void ChangeToComma()
{
var someUserInput;
char arr[] = someUserInput.ToCharArray();
for (int i = 0, i < someUserInput.Length; i++)
{
if (char[i] == ".")
{
char[i] = ",";
}
}
}
That would be the logic I would use (maybe not correct but I just wanted to show better what I want to do).
I'm just starting with other than console apps so I'm stuck here :/
What I don't even have a slightest idea about (how to do it) is:
How to go through every single char in a specified DataGridView cell?
How to avoid changing every single dot in every cell of this DataGridView? Some of them are with text so they might contain dots.
You can do it by replacing the comma for a dot using the replace method contained in system
double value = double.Parse(dataGridViewTest.Rows[4].Cells[2].Value.ToString());
dataGridViewTest
.Rows[4]
.Cells[2].Value = value.ToString("N2");
"N2" as a parameter for method to string will set the value as decimal with two digits at the end.
You can also validate the input before saving the data to avoid users insert wrong the information in a wrong format.

Textbox Number Formating & start with zero & accept only Numbers

I am using below Property example to make some calculation on textbox and if textbox is null I am assigning zero to it so calculation won't fail as you can see I am using Math.Round and I want to make several checks on these textbox input like
textbox that only accepts numbers I searched and found method 1
I want my textbox to be formated I searched and found Method 2
Now my question is ..
Is there any way to mareg all these method in the property method I am using
so my code won't be like "spaghetti code" ?
is there any better ways to do these checks ?
Thank you in advance
Property example
public double ItemPriceResult
{
get
{
return Math.Round(ItemCost * RevenuePercentage / 100 + ItemCost, 0);
}
}
Method 1
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
{
MessageBox.Show("Please enter only numbers.");
textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
Method 2
textBox1.Text = string.Format(System.Globalization.CultureInfo.GetCultureInfo("id-ID"), "{0:#,##0.00}", double.Parse(textBox1.Text));
UPDATE after some answers
MaskedTextBox seems fit my needs I read and searched and below some question
if you kindly would like to help me
I need to use MaskedTextBox because I can set it to accept
number and I can also force number formating so
also I need to make number textboxs easer to read for users
so 1000 will be come 1,000
and 10000 will be come 10,000
then according to Microsoft Docs formating MaskedTextBox to fit my needs
Masked MaskedTextBox with 999,999,999,
second I do not want the PromptCharto be visible I google it but none of search result did it
Try this , it will accept only numbers and u can format the string as u want using regex.
public static string ToMaskedString(this String value)
{
var pattern = "^(/d{2})(/d{3})(/d*)$";
var regExp = new Regex(pattern);
return regExp.Replace(value, "$1-$2-$3");
}
You have a TextBox. Alas you don't tell what kind of TextBox you use. System.Windows.Forms.TextBox? System.Web.UI.MobileControls.TextBox?
You write "if text box is null I am assigning zero to it". I assume that you mean that if no text is entered in the text box you assume that 0 is entered.
Furthermore you want to format the output of the text box whenever the text is changed. So while the operator is typing text you want to change this text? For the operator this is very annoying.
Wouldn't you prefer that the operator is obliged to type his text in the format you desire, helping him visually. For this you may use the class MaskedTextBox
The MaskedTextBox has a property Mask, which forces the operator to type in a certain format. I'm not really familiar with what you do with the format {0:#,##0.00}, but I assume you want the output double in a real format with two digits after the decimal point using the decimal point and the thousand separator as common in the current culture.
via the designer put in initialize component:
this.maskedTextBox1.Mask = "99990.00";
after adding the event for text changed:
private void maskedtextBox1_TextChanged(object sender, EventArgs e)
{
double enteredValue = 0.0; // value to use when empty text box
if (!String.IsNullOrEmpty(this.maskedtextBox1.Text))
{
enteredValue = double.Parse(maskedTextBox1.Text, myFormatProvider)
}
ProcessEnteredValue(enteredValue);
}
}
After your edit, the specifications have changed.
While entering the number in the text box, the operator should not have any visual feedback of the formatting of his number.
The operator is free to enter the real number in any commonly used format.
The value of the text box should not be used while the operator is editing the text box.
Only after editing is finished, the value of the text box should be interpreted for correctness, and if correct it should be used.
The actually used value should be displayed in the text box in a defined format.
The desire not to show any visual feedback while entering is understandable. After all, the program doesn't care whether the operator types 1000, 1000.00, or even 1.0E3.
The MaskedTextBox is especially used to force the operator to enter his number in a given format. Since this is not desired, my advise would be to use a TextBox instead of aMaskedTextBox.
However, because you give the operator the freedom to enter his number in any way he wants, including copy-paste, repairing typing errors, etc. you'll have to add the possibility for the user to express to the program that he has finished entering the number.
An often used method in the windows UI would be a Button. Another possibility would be the enter button. Be aware though that this is not really standard within windows. It might make learning your program a little bit more difficult.
So after the operator notified that he finished editing and the corresponding event function is called, your code could be:
// Get the numberformat to use, use current culture, or your own format
private readonly IFormatProvider myNumberFormat = CultureInfo.CurrentCulture.NumberFormat
private void OperatorFinishedEditing(TextBox box)
{
// read the text and try to parse it to a double
// accepting all common formats of real numbers in the current culture
bool valueOk = true;
double resultValue = 0;
if (!String.IsNullOrEmpty(box.Text))
{
bool valueOk = Double.TryParse(box.Text, out resultValue);
}
if (valueOk)
{
box.Text = FormatResultValue(resultValue);
ProcessValue(resultValue);
}
else
{
ShowInputProblem();
}
}

NumericUpDown negative input by user possible?

I have several groupBoxes-controls with a NumericUpDown-control in each on of them. The NumericUpDowns have a small modification - they can also decrement in the negative range of decimal. Here is the code:
//Add KeyDown event to the numericUpDown control
numericUpDownGBPC12_angleRange.KeyDown += new KeyEventHandler(numericUpDownNegative);
The code of the function numericUpDownNegative is as follows:
void numericUpDownNegative(object sender, KeyEventArgs e)
{
NumericUpDown temp = (NumericUpDown)sender;
temp.Value -= temp.Increment;
sender = (object)temp;
NumericUpDown temp = (NumericUpDown)sender;
}
Suggestions for improving the code above are most welcome however I'm more interested if it is possible to enable negative input in a NumericUpDown. The above code works but when I try to put a negative number I get something weird. This behaviour does not apply for a non-modified NumericUpDown.
Example:
Let's say numericUpDownGBPC12_angleRange has a minimum of -70.0000000000 and a maximum of 70.0000000000, which I have set by the Minimum/Maximum property parameters of the control. The starting value of the control is 0.0000000000. If I push the Down-button, I get accordingly -0.0000000001, -0.0000000002, -0.0000000003 etc. until I reach -70.0000000000. However if I decide to type -x.xxxxxxxxxx (let's say -24.2398324119) I get x-0.0000000000 (4-0.0000000000). So not only I cannot enter the full number 24 (it seems the NumericUpDown takes the last typed digit in this case, which is 4), but I get the whole part after the point completely annihilated unless it was set by using the case in which case the problem is only with the part before the point. So only the first digit (on the most left of the number) can be changed. :-/
I was thinking of using textBox-controls however the amount of number fields I have as part of the interface will create a huge overhead because of the parsing of each and every textBox (we all know that sadly many users love to experiment with things that where never intended to be experimented with ;)) to make sure a certain number is entered. Despite the negative-thingy the NumericUpDown has really nice feature such as - only a digit can be entered and you can also specify the precision, the range of values etc.
So again the question is - is it possible for a NumericUpDown to accept negative input by the user?
Problem was in the KeyDown-event (had to remove it completely) and also in the format I was trying to input as a number. I have the ',' seperator and not the '.' in my Visual Studio (due to localization). So typing '.' made the NumericUpDown go berserk.

how can I take the value of a NumericUpDown in C# and use it for something ex. use as an int

I'm making a Higher Lower game, and the number of tries the user has to guess the computer's number, I want to set using a NumbericUpDown.
How can I do this?
(Should I paste my code here so you can see what I have so far?)
Set the Value property of the control? See the examples here.
For example,
this.upDown.Value = 5;

Test for filled textboxes and correct type of data

I am working in C#, Windows Form Application.
I have 6 text boxes that accept user input. When the 'Submit' button is clicked it stores the values in an array. I want to create something to check the text boxes for two things 1.) there is something in the text boxes and 2.) the information is only a number, nothing else.
I have been told that a try catch loop will be able to do this, but I have yet to figure out how.
Thank you for any help you can provide
You do not want to use a try catch block for this - you should not use exceptions for standard application flow as it is a relatively expensive option.
Checking if it is empty
string.IsNullOrEmpty(textbox1.Text);
Checking if it is a number
int result;
int.TryParse(textbox1.Text), out result);
// In button_click event or somewhere like that
if (!this.CheckInput(txt_TextBox1))
return;
if (!this.CheckInput(txt_TextBox2))
return;
if (!this.CheckInput(txt_TextBox3))
return;
// Everything OK, do something
Then a method like this:
private bool CheckInput(TextBox textbox) {
int test;
if (!int.TryParse(textbox.Text.Trim(), out test)) {
MessageBox.Show("Invalid input");
return false;
}
return true;
}
To check if something is in the textbox you can call the string.IsNullOrEmpty method.
As for checking if a Textbox only contains numeric values, you might want to consider preventing users from entering non-numeric values. This would be a more user friendly approach than preventing it after entering the values.
You can use isNullOrEmtpy as Bas suggested above in order to check if there is any user input.
For numeric numbers only, i suggest you use Regex. You can find a solution here

Categories

Resources