Click here to Skip to main content
15,888,062 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a texbox(for hours) which allows only maximum of 4 digits i.e maximum two digits before decimal point, a decimal point and then a single digit.And if the user enters just values like 10 or 2, it will append ".0" by default.
Now if users enters values like ex: 10.5 or 2.5 or 2.0 or 12.5 it should accept, but when the user enters anything apart from the above two formats like ex: 1111 or 3356 it should not allow.
So can you please tell me how to implement this in C#(wpf)?


i need to implement this in wpf
Posted

1 solution

ehm... what you are asking for is:
> You want a textbox to collect a "floating point" value
> Check if it adheres to a certain set of rules
> And either give a message back, (if it's in the wrong format), or continue to the next step in you program?

That's not too hard!
Googling would have given you all the answers for this process. (I recommend that in the future, you divide your issue into steps as I have done above, and Google for a solution to each). Many people have ignored this question for being "too basic" or "lazy" to answer.

Now, I'm giving you a functioning, very simple way to do what I interpret you to want, this is not the best way for you to do this, nor is it a good thing for you to just copy it, I've commented as best I can in the ten minutes I've used on this, so please try to learn from this, so that you don't have to ask about these things, which are very simple. (I get that what I see as basic and simple can be difficult for others, and vica versa, but this is pretty fundamental things to use conditionals to see if something is something or other)

(The code provided should work, just create a new project, and copy whats needed where you need it, or use the entire code)

C# code:
C#
using System;
using System.Windows;

namespace FloatValidation
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnCheck_Click(object sender, RoutedEventArgs e)
        {
            string varInput; // String variable to hold the input from the textbox
            double varNumber; // Double variable to hold the parsed/converted input string as a number/value

            // conditionals to check through rules for valid input (should be moved to separate method for ease of use
            if (txtBoxInput.Text != "") // Check to see if user have entered anything in the TextBox
            {
                varInput = txtBoxInput.Text; // Assign the string to the varibale from the input textbox
                if (Double.TryParse(varInput, out varNumber)) // Check if string contains only characters that are valid as a double value/number
                {
                    if (varNumber < 100) // Is the value less than 100 or prevents anything other than two digits in front of the decimal point separator (can be set to 12,1 and nobody can give a value larger than 12)
                    {
                        varNumber = Math.Round(varNumber, 1, MidpointRounding.ToEven); // Rounds the value from "loads" of decimals to only 1 (change the '1' to any number)
                        MessageBox.Show("You have registered a valid input:\nYour registered input is:\n" + varNumber); // Displays a textbox confirming that the value given to the program is valid, and returns the value for review

                        ///
                        /// Your code to store the value goes here!
                        ///
                    }
                    else
                    {
                        MessageBox.Show("The texfield cannot contain a value above 99.9"); // Feeback of bad input
                    }
                }
                else
                {
                    MessageBox.Show("The textfield can only contain a valid number! \ne.g. 15.5"); // Feedback of bad input
                }
            }
            else
            {
                MessageBox.Show("The textfield can't be empty"); // Feedback of bad input
            }
        }
    }
}


WPF code:
XML
<window x:class="FloatValidation.MainWindow" xmlns:x="#unknown">
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Check if float!" Height="176" Width="230" Background="#DDDDDD">
    <grid>
        <textbox height="23">
                 HorizontalAlignment="Left"
                 Margin="45,50,0,0"
                 Name="txtBoxInput"
                 VerticalAlignment="Top"
                 Width="120" />
        <button content="Check!">
                Height="23"
                HorizontalAlignment="Left"
                Margin="69,91,0,0"
                Name="btnCheck"
                VerticalAlignment="Top"
                Width="75"
                Click="btnCheck_Click" />
        <label content="Check Input">
               Height="28"
               HorizontalAlignment="Left"
               Margin="45,12,0,0"
               Name="lblHeading"
               VerticalAlignment="Top"
               Width="120"
               HorizontalContentAlignment="Center"
               FontWeight="Bold" />
    </label></button></textbox></grid>
</window>


Sources:
- Level up your 'Google Fu' here[^]
- MSDN - if-else (C# Reference)[^] (how to use conditions in your program)
- MSDN - MessageBox Class[^] (Shows how to use the MessageBox in detail | can be used to have the user confirm the that the value was correct before storing to database)
- MSDN - Math.Round Method [^] (Rounds a numeric value to either X decimals or a whole number; other conditions exists)
- MSDN - Double.TryParse Method (String, Double)[^] (try parse method for doubles/floats | best used for checking if textbox input string is valid numeric value, in your case)
- CodeProject - Check If A String Value Is Numeric[^] (Check if a string is numeric)

Something everyone should be familiar with:
- MSDN - Removing Unused Usings[^]

Good luck! and remember to rate and accept this answer as appropriate!

-Frank
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900