How to set character limits to a textbox that is read-only? - c#

I am creating a calculator app in visual studio. I created some buttons in windows form that will input numbers in a textbox. Since the input did not came from a keyborad, the MaxLength properties is not working for me. I set the textbox to read only so that the user can only input through the buttons. How can I set the character limits (characters because I add "," in thousands, ten thousands etc. I only allow 12 digits + the 3 commas making a total of 15 characters in a textbox) that in a textbox that is filled with buttons?

You can create a custom TextBox that ensures the text is never larger than the MaxLength property.
class RestrictedTextBox : TextBox
{
public override string Text
{
get
{
return base.Text;
}
set
{
if (value.Length > MaxLength)
base.Text = value.Substring(0, MaxLength);
else
base.Text = value;
}
}
}

Really need more information as to what type of app your using to build the calculator like WPF/Winforms/Web.
Since your using a UI element, and this is strictly a UI display you could do this in the code behind file for the UI page.
You'll need to check the length of the textbox to determine if the length is under whatever your limit is, and if so then add the button's value to the the text property for that textbox
something like the following
If (textbox.Text.Length < 15)
textbox.Text += Button.Content.Value
As for inserting the commas you'll again need to check the length and can insert a comma at the correct spot when needed.

Related

How do I calculate values from multiple textboxes and display in seperate box? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I got 4 textboxes that I want to put values in, and I want it to find the average number from the values of the inputted values to the 4(or more) textboxes.
I want the average to display in a readonly box (is richtextbox good for this?).
You can use both a RichTextBox and normal TextBox for this. To ensure that it is read-only, in the designer page do the following;
Select the TextBox > Scroll under properties window > Behavior Section > Read-Only property
Setting this property to true will make the TextBox non-editable by the user.
After you have the 4 editable TextBoxes and 1 non-editable, you can implement something like the following to add up the numeric values of TextBoxes and display it in the readonly TextBox.
private void AverageAndDisplay()
{
try
{
//Convert values to numeric
decimal one = Convert.ToDecimal(textBox1.Text);
decimal two = Convert.ToDecimal(textBox2.Text);
decimal three = Convert.ToDecimal(textBox3.Text);
decimal four = Convert.ToDecimal(textBox4.Text);
//Find the average
decimal average = (one + two + three + four) / 4.0m;
//Show the average, after formatting the number as a two decimal string representation
textBox5.Text = string.Format("{0:0.00}", average);
}
catch(Exception e) //Converting to a number from a string can causes errors
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
So you should have this steps:
Create 4 textboxes. Let's this buttons has ID Value1Txt, Value2Txt, Value3Txt, Value4Txt
Add button with text Calculate Average Value. The ID of the button should be CalculateAverageBtn
Add the Label in which you will show the Average. The ID of this Label should be AverageValueLbl
Attach OnClick event on the CalculateAverageBtn. You could do it using the signature of the button OnClick="CalculateAverageBtn_Click" or doing it in the code
//this should be inside InitializeComponents method
CalculateAverageBtn.OnClick += CalculateAverageBtn_Click;
protected void CalculateAverageBtn_Click(object sender, EventArgs e)
{
//...code
}
Now in the body of CalculateAverageBtn_Click you should Parse the values of the TextBoxes and calculate the average. You could do this using decimal.TryParse method
decimal value1 = 0;
if(!decimal.TryParse(Value1Txt.Text, out value1)
{
//if you come in this if the parsing of the value is not successful so
you need to show error message to the user. This happen when the user
enters text like 123Test, this is not a number. So you need to show
error message
}
Create a label in which you will show the error message. Let's call it ErrorLbl. So when the parsing is not successful we will write in this label the error message.
if(!decimal.TryParse(Value1Txt.Text, out value1)
{
ErrorLbl.Text = "The value of value 1 textbox is not valid number"
return; //exit the button click method
}
Calculate the average of 4 textboxes and write it in the AverageValueLbl. This should be in button event click
AverageValueLbl.Text = (value1+value2+value3+valu4)/4.ToString();
Try to understand what you are doing, don't copy/paste mindlessly code. This is pretty much beginner programming. For sure this is homework, so try to understand it because in the future harder homeworks you will be lost.

C# Removing last two characters from textbox

I have a textbox which I'm trying to implement automatic formatting on for a phone number.
I would like to remove the last two characters of the textbox if the user presses the delete key and the last character of the string in the textbox is '-'.
I am attempting to do this through substring removal, but with no luck. Thanks
private void phoneNumberTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
if (phoneNumberTextBox.Text.Length != 0)
{
if (Convert.ToChar(phoneNumberTextBox.Text.Substring(phoneNumberTextBox.Text.Length - 1)) == '-')
{
phoneNumberTextBox.Text.Substring(0, phoneNumberTextBox.Text.Length - 2);
}
}
}
Substring() returns a new string instance and leaves the current instance unchanged. Because of this, your call just creates a new temporary string but because you don't do anything with it, it gets thrown away immediately.
To make the change stick, you need to assign the result of Substring() back to the textbox, like so:
phoneNumberTextBox.Text = phoneNumberTextBox.Text.Substring(0,
phoneNumberTextBox.Text.Length - 2);
Make sure you check the length of the string first to avoid problems with handling short string (less than 2 characters).
Also, if you want to limit the number of characters in the textbox, just use the MaxLength property instead. You don't have to deal with handling length and typing that way.
For the 2 char removal could do:
phoneNumberTextBox.Text = phoneNumberTextBox.Text.Remove(phoneNumberTextBox.Text.Length - 2, 2);
For the key pressing part might be that you have to enable the KeyPreview on you form.
Wow sry for the editing doing mistakes all over.

How do I make a richtextbox limited to only digits with a max number? (Cap)

Hey guys I wanted to make a richtextbox that only supports numbers and cant go above, 500 for example.
how would I go by doing that? thanks
I would use the keydown event to check if the pressed key is one of the keys you allow. With numbers it is pretty simple, maybe add ',' and '.' or other characters of your choice.
I'm not sure about the specifics but you can add something like
myRichTextBox.OnTextChanged() {
int number = 0;
bool checkInt = Int32.TryParse(myRichTextBox.Text, out number); //this checks if the value is int and stores as true or false, it stores the integer value in variable "number"
if ( checkInt = true && number > 500 ) //check if value in textbox is integer
{
myRichTextBox.Text = number.ToString();
}
else
{
DialogBox.Show("Please Enter Numbers Only");
myRichTextBox.Text = "";
}
}
You probably have to read the Int32.TryParse usage but brushing up this code should do what you want.
You can also put this code in a button onclick method to check that the value in textbox is integer before using the text.

How to replace the TextBox Caret

i have a text box binded with a mobile number and takes - after each 3 charecters.say max characters for mobile number would be 10 and after 3 character a - would be shown (Say example i have 1234567890 )(this mobile number would be replaced with 123-456-7890).
My question here is i need to remove - from the text box and make it an empty.can any one help me in this.this is all done in C#
This is my code which i have tried.
this is associated property i have set
public static readonly DependencyProperty AssociatedElementProperty = DependencyProperty.Register("AssociatedElement", typeof(FrameworkElement), typeof(NumericKeyBoard), null);
this.caretPosition = associatedTextBox.SelectionStart;
if (associatedTextBox.Tag.ToString() == "mobile" && associatedTextBox.Text.Substring(this.caretPosition - 1, 1) == "-")
{
associatedTextBox.Text = associatedTextBox.Text.Remove(this.caretPosition - 1, 1);
this.caretPosition--;
}
Consider using a modified TextBox Control like the MaskedTextBox

C# Texbox's 'MaxLength' Property - Faults (Winform)

There might be some workaround for this one - however, I'm not sure what it is at the moment. After setting the MaxLength property of a textbox, I am unable to manually exceed the MaxLength of the textBox. On the other hand, if I were to create a loop which programmatically added characters to the textbox - this loop could exceed the maxLength property.
textBox1.MaxLength = 5; // I am now unable to manually type in more than 5 chars.
for (int i = 0; i < 20; i++)
{
textBox1.AppendText("D");
}
// Textbox now holds 20 chars.
Without having to write more lines of code to take a portion of this data, is there a way to ensure that the maxlength property is not exceeded?
Regards,
Evan
MaxLength: Gets or sets the maximum number of characters the user can type or paste into the text box control. (Forms) http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.maxlength.aspx and Gets or sets the maximum number of characters allowed in the text box. (web) http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.maxlength.aspx
In other words, that's the point of MaxLength - it's all about controlling user input. Since you own the textbox to begin with, you don't need to set your own hard programmatic restrictions.
So in short, no - you can't change this behavior without overriding some other functionality - for instance on OnChanged - or adding the conditional tests like those shown by Ben and Sres.
From the MSDN docs:
In code, you can set the value of the
Text property to a value that has a
length greater than the value
specified by the MaxLength property.
This property only affects text
entered into the control at run time.
If you want to prevent Text from being longer than MaxLength, some extra code is needed.
How about:
textBox1.MaxLength = 5;
for (int i = 0; i < 20 && i < textBox1.MaxLength; i++)
{
textBox1.AppendText("D");
}
Not sure if that counts as "more lines of code" but it's a pretty simple extra check.
textBox1.MaxLength = 5;
while(textBox1.Text.Length <= textBox1.MaxLength)
textBox1.AppendText ("D");
This should do it I believe
MaxLength property prevent user to type more than n characters. but when you set the Text property programatically,your textbox will show the value of its Text property even if its length exceed the value MaxLength
so you have to check if your loop exceed the maxlength or not.
As far as I know setting the maximum width of a textbox only enforce this restriction to end user who is entering values thorough UI. This restriction doesn't apply on code
MaxLength is used when you don't want the user to be able to input more than the assigned amount. However, programatically, it can be overridden. This is what append text does:
public void AppendText(string text)
{
if (text.Length > 0)
{
int start;
int length;
this.GetSelectionStartAndLength(out start, out length);
try
{
int endPosition = this.GetEndPosition();
this.SelectInternal(endPosition, endPosition, endPosition);
this.SelectedText = text;
}
finally
{
if (base.Width == 0 || base.Height == 0)
{
this.Select(start, length);
}
}
}
}
You could write an extension method, and use it to append text instead of .AppendText()
void Main()
{
var t = new TextBox();
t.MaxLength=5;
t.Text = "123";
t.AppendTextRespectMaxLength("456789");
t.Text.Dump(); // prints 12345
}
public static class ExtensionMethods
{
public static void AppendTextRespectMaxLength(this TextBox textbox,string newText)
{
if(textbox.Text.Length + newText.Length <= textbox.MaxLength)
{
textbox.Text += newText;
}
else
{
var remaining = textbox.MaxLength - textbox.Text.Length;
var subPortion = newText.Substring(0,remaining);
textbox.Text += subPortion;
}
}
}

Categories