How to replace the TextBox Caret - c#

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

Related

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

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.

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.

Reading first 3 numbers in a 13 digit control number in c#

I have a program that generates a control number. Control number contains 13 numbers. The first 3 numbers is generated if the user is a maritime education, it is 100, but if the user is a general education, it is 101, then the following 5 numbers is a random numbers. Then the last 5 digits is the ID number of the user.
Code :
Random rand = new Random();
int startingDigits;
if (CmbEducation.SelectedItem.Equals("Maritime Education"))
{
startingDigits = 100;
string IdNumber = TxtIDnum.Text;
string controlNumber = string.Format("{0}{1}{2}",
startingDigits, rand.Next(10000, 99999).ToString(), IdNumber);
TxtControlNum.Text = controlNumber;
}
else if (CmbEducation.SelectedItem.Equals("General Education"))
{
startingDigits = 101;
string IdNumber = TxtIDnum.Text;
string controlNumber = string.Format("{0}{1}{2}",
startingDigits, rand.Next(10000, 99999).ToString(), IdNumber);
TxtControlNum.Text = controlNumber;
}
My problem is, I want to make an if..else condition. but i want to read the first 3 numbers of the control number how do i do it? Thanks :)
edited :
I am using the control number in another form now for password. So i want to read the first 3 numbers to get if the user is a marine education or a general education.
Now, I am in another form, i just copied the text from the login page where the password is the control number to the textbox in another form. so how do i read first 3 numbers inside a textbox?
Not sure if I'm reading your question correctly, but if all you need is to read the first three digits, just do:
var start = new String(controlNumber.Take(3).ToArray());
or
var start = controlNumber.Substring(0,3);
It's not clear what you mean by "read inside a textbox". Do you want to read them from a textbox? Then try:
TextboxName.Text.Substring(0,3);
If you want to place them in a textbox, use:
TextboxName.Text = controlNumber.Substring(0,3);
Update: I'll give this one more try. This should be self-explanatory, assuming you've got start as above:
if (start.Equals("100"))
{
// Do something
}
else if (start.Equals("101"))
{
// Do something else
}
else
{
// ...take a nap?
}
var controlNumberPrefix = myTextBox.Text.Substring(0, 3);
switch (controlNumberPrefix)
{
case "100":/* Maritime education - do something */ ; break;
case "101":/* Gen education - do something */ ; break;
}
or
var controlNumberPrefix = myTextBox.Text.Substring(0, 3);
if(controlNumberPrefix == "100")
// Do something
else if (controlNumberPrefix =="101")
// Do something
Edit:
Its the same thing with textbox. Just use the Text property of the textbox.

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