How can i know the last change that the user did in the text in RichTextBox?
Is there a function?
Or I need to build to it a function?
Add an event to your textbox. Select your textbox, go to properties, in event tab you will see different events. Find TextChanged event. Add that event to your code.
This function will trigger everytime textbox is changed. You can write your logic in that function.
It provides an event called TextChanged. You'll need to define an EventHandler and specify what is to happen, when the text changes.
For example:
private void rtb_TextChanged(object sender, EventArgs e)
{
char c = rtb.Text.ElementAt(rtb.Text.Length);
if(c == mystring.ElementAt(mystring.Length))
//is equal
mystring = rtb.Text; //save string for next comparison
}
and now you need to add the eventhandler to the event like
rtb.TextChanged += rtb_TextChanged;
Look here for documentation.
UpdatedChar would contain the newly added character to the textbox1
OldValue would always contain the Old Value in the textbox1
From your example : if my text is: "Text" and than I click 8 so the Text will be "Text8" so the char is 8.
UpdatedChar=8 and
OldValue = Text
public string OldValue = string.Empty;
public char UpdateChar;
private void textBox1_TextChanged(object sender, EventArgs e)
{
var newText = sender as TextBox;
foreach (var val in newText.Text)
{
if(!OldValue.ToCharArray().Contains(val))
UpdateChar = val;
}
OldValue = newText.Text;
}
Related
I have created the following GUI:
I enter my text in a TextBox (#1 in the picture). I have a Button (#2 in the picture) which should change the input in the TextBox to uppercase so I wrote the following code:
private void tuUpperCase(object sender, RoutedEventArgs e)
{
if (crossBox.IsChecked == true)
{
machineName.Text.ToUpper();
}
}
string.ToUpper() does not modify the string, just returns the modified string. So you need to set new modified value to the machineName.Text.
private void tuUpperCase(object sender, RoutedEventArgs e)
{
if (crossBox.IsChecked == true)
{
machineName.Text = machineName.Text.ToUpper();
}
}
The ToUpper method returns a new string, it does not change the machineName.Text property.
Returns a copy of this string converted to uppercase.
If you assign its return value (the new uppercase string) to machineName.Text it will work.
machineName.Text = machineName.Text.ToUpper();
One issue with this is that the caret position will be reset, when the new text is set. You could store the CaretIndex, modify the text and then reassign it to preserve the position.
private void tuUpperCase(object sender, TextChangedEventArgs e)
{
if (crossBox.IsChecked == true)
{
var caretIndex = machineName.CaretIndex;
machineName.Text = machineName.Text.ToUpper();
machineName.CaretIndex = caretIndex;
}
}
From your comment I assume that you use a CheckBox event like Checked or Unchecked. However, this will only convert the text to uppercase the moment you check the CheckBox, everthing typed afterwards is still lowercase. A solution to this would be to use the TextChanged event of the TextBox, which would convert the text as you type.
I have one TextBox with binding on DateTime type. I need to get a dot after first 2 chars and second 2 chars, for example: 12.12.1990.
I'm using behavior in TextChanged event, that code:
void tb_TextChanged(object sender, TextChangedEventArgs e)
{
int i = tb.SelectionStart;
if (i == 2 || i == 5)
{
tb.Text += ".";
tb.SelectionStart = i + 1;
}
}
That is working, but if I want to delete text by backspace, obviously I can't delete dots, because event is called again.
What is better way to solve it?
Solved
It works
But if you can, you may fix my algorithm.
public string oldText = "";
public string currText = "";
private void TextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
oldText = currText;
currText = TextBox1.Text;
if (oldText.Length > currText.Length)
{
oldText = currText;
return;
}
if (TextBox1.Text.Length == currText.Length)
{
if (TextBox1.SelectionStart == 2 || TextBox1.SelectionStart == 5)
{
TextBox1.Text += ".";
TextBox1.SelectionStart = TextBox1.Text.Length;
}
}
}
I would do it in the KeyPress event, so you can filter by what kind of key it was (using the KeyChar argument with Char.IsLetter() and similar functions).
Also, add the dot when the next key is pressed. If the user has typed "12", don't add a dot yet. When the user presses 1 to add the second "12", add it then (before the new character).
Use String Format in the xaml control like so
StringFormat='{}{0:dd.MM.yyyy}'
I just tested it and this will even convert slashes to the dots.
For example
<TextBox.Text>
<Binding Path="Person.DateOfBirth" UpdateSourceTrigger="LostFocus" StringFormat='{}{0:dd.MM.yyyy}'></Binding>
</TextBox.Text>
If you are using a datepicker then you will need to override its textbox template as in the link below with the String Format above.
This link may help if if you are trying to apply it to a datepicker.
I recommend you to use a DateTimePicker and change its Format property to Short. Another option is to change your TextBox to a MaskedTextBox and changing its Mask property to ShortDate (00/00/0000) .DateTimePicker allows you not to do much about validating datetime values. But if you use a MaskedTextBox you should validate it. Sample link shows how to do validation.
I have modified above code
private void txt_in1_TextChanged(object sender, TextChangedEventArgs e)
{
int i = txt_in1.SelectionStart;
if (bsp1 != 1)
{
if (i == 2)
{
txt_in1.Text += ":";
txt_in1.SelectionStart = i + 1;
}
}
}
private void txt_in1_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Back)
{
bsp1 = 1;
}
else
{
bsp1 = 0;
}
}
I have taken another event which is keyup (equivalent keypress event), In that whenever backspace is detected it will flag bsp1 variable, which intern stop the text change event to put ":". here "bsp1" is define as global variable. (Code is for wpf, c#).
This is my LostFocus event handler:
private void txtThrow_LostFocus(object sender, System.EventArgs e)
{
TextBox source = (TextBox)sender;
if (source.Text == "")
source.Text = "0";
}
This actually interferes with txtThrow_KeyPress, so that after I do my processing on my TextBox which accepts to only hold one character, I find it having two: mine and this zero you see here!! What I want to do is to keep txtThrow_KeyPress exactly as it is, but whenever the user types nothing, I want to enforce a zero.
What I can understand from here is that txtThrow_LostFocus is triggered before txtThrow_KeyPress is done with its job, since at the time txtThrow_LostFocus is triggered, the text is still empty. How can that be correct?!
I would recommend using the TextChanged event instead of the KeyPress event. I am assuming the text box could be empty already, and the user presses Backspace or something of the nature.
TextChanged event is triggered every time the text is changed within the field.
And the code you have should work perfectly fine when you fill the new event handler method with such. However, you may need to use
private void txtThrow_LostFocus_TextChanged(object sender, System.EventArgs e)
{
TextBox source = (TextBox)sender;
if (source.Text == "" || source.Text == null)
source.Text = "0"
}
Hope this helps!
Try to this code
private void txtThrow_LostFocus_TextChanged(object sender, System.EventArgs e)
{
TextBox source = (TextBox)sender;
if (string.nullorempty(source.text)
source.Text = "0"
}
In a TextBox I'm monitoring the text changes. I need to check the text before doing some stuff. But I can only check the old text in the moment. How can I get the new Text ?
private void textChanged(object sender, EventArgs e)
{
// need to check the new text
}
I know .NET Framework 4.5 has the new TextChangedEventArgs class but I have to use .NET Framework 2.0.
Getting the NEW value
You can just use the Text property of the TextBox. If this event is used for multiple text boxes then you will want to use the sender parameter to get the correct TextBox control, like so...
private void textChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if(textBox != null)
{
string theText = textBox.Text;
}
}
Getting the OLD value
For those looking to get the old value, you will need to keep track of that yourself. I would suggest a simple variable that starts out as empty, and changes at the end of each event:
string oldValue = "";
private void textChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if(textBox != null)
{
string theText = textBox.Text;
// Do something with OLD value here.
// Finally, update the old value ready for next time.
oldValue = theText;
}
}
You could create your own TextBox control that inherits from the built-in one, and adds this additional functionality, if you plan to use this a lot.
Have a look at the textbox events such as KeyUp, KeyPress etc. For example:
private void textbox_KeyUp(object sender, KeyEventArgs e)
{
// Do whatever you need.
}
Maybe these can help you achieve what you're looking for.
Even with the older .net fw 2.0 you should still have the new and old value in the eventArgs if not in the textbox.text property itself since the event is fired after and not during the text changing.
If you want to do stuff while the text is being changed then try the KeyUp event rather then the Changed.
private void stIDTextBox_TextChanged(object sender, EventArgs e)
{
if (stIDTextBox.TextLength == 6)
{
studentId = stIDTextBox.Text; // Here studentId is a variable.
// this process is used to read textbox value automatically.
// In this case I can read textbox until the char or digit equal to 6.
}
}
I am using c# winform.
I have 2dimensional array of text boxes I want them to accept only Letters from A-I I've created the method but that works for only one text box.
Here is my code:
textbox[i,j].Validated+=new EventHandler(TextBox_KeyPress);
private void TextBox_KeyPress(object sender, EventArgs e)
{
bool bTest = txtRegExStringIsValid(textbox[1,1].Text.ToString());
ToolTip tip = new ToolTip();
if (bTest == false)
{
tip.Show("Only A-I", textbox[1,1], 2000);
textbox[1,1].Text = " ";
}
}
private bool txtRegExStringIsValid(string textToValidate)
{
Regex TheRegExpression;
string TheTextToValidate;
string TheRegExTest = #"^[A-I ]+$";
TheTextToValidate = textToValidate;
TheRegExpression = new Regex(TheRegExTest);
if (TheRegExpression.IsMatch(TheTextToValidate))
{
return true;
}
else
{
return false;
}
}
Can anyone please guide what should I do make this code work for all text boxes?
if this works for textbox[1,1] you could register your private void TextBox_KeyPress(object sender, EventArgs e) as eventhandler for all your textboxes and instead of textbox[1,1] you could use ((TextBox)sender)
i want text boxes to accept only letters from a-i actually i am trying to make sudoku
There's a much simpler solution than regular expressions, and you don't even need to handle the Validated event to implement it.
In a situation like this, where there are only certain characters that you want to prevent the user from entering, handling the KeyDown event is a much better solution. The user gets immediate feedback that the letter they tried to enter was not accepted. The alternative (the Validating and Validated events) actually wait until the user tries to leave the textbox to rudely alert them that their input was invalid. Especially for a game, this tends to break concentration and isn't particularly user-friendly.
Doing it this way also makes it irrelevant which individual textbox raised the event. Instead, you will handle it the same way for all of the textboxes—by completely ignoring all invalid input.
Here's what I'd do:
First, attach a handler method to your textbox's KeyDown event. You can do this from the Properties window in the designer, or you can do it through code, as you have in the question:
textbox[i,j].KeyDown += TextBox_KeyDown;
Then, you need to put the logic into your event handler method that determines if the key that the user just pressed is in the allowed range (A through I), or outside of it:
private void TextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Determine if the keystroke was a letter between A and I
if (e.KeyCode < Keys.A || e.KeyCode > Keys.I)
{
// But allow through the backspace key,
// so they can correct their mistakes!
if (e.KeyCode != Keys.Back)
{
// Now we've caught them! An invalid key was pressed.
// Handle it by beeping at the user, and ignoring the key event.
System.Media.SystemSounds.Beep.Play();
e.SuppressKeyPress = true;
}
}
}
If you want to restrict the user to typing in only one letter, you can add code to handle that in the above method, or you can take an even simpler route and let the textbox control handle it for you automatically. To do that, set the MaxLength property of the textbox to true, either in the designer or through code:
textbox[i,j].MaxLength = true;
Check the text of the sender instead of whatever textbox[1,1] is.
Use the sender parameter of the event handler to identify the textbox responsible for the event.
The first thing that will help you is casting the sender of your event to a TextBox like this:
(Also, as Cody Gray said, this is a TextBox_Validated event, not a KeyPress event so I've renamed it appropriately)
private void TextBox_Validated(object sender, EventArgs e)
{
TextBox tb = sender as TextBox()
if (sender == null)
return;
bool bTest = txtRegExStringIsValid(tb.Text.ToString());
ToolTip tip = new ToolTip();
if (bTest == false) {
tip.Show("Only A-I", tb, 2000);
tb .ext = " ";
}
Next you need to actually get into that code for every textbox. There are two obvious approaches to that, you can either assign the eventhandler to each textbox in the array or you can use a custom textbox which always does this validation and then add that to your array.
Assign eventhandler to textboxes
foreach(var tb in textbox)
{
tb.Validated += new EventHandler(TextBox_KeyPress);
}
Create custom textbox control
Create the custom text box control (Add a user control to the project) and then just use it exactly as you would a normal textbox.
public partial class ValidatingTextBox: TextBox
{
public ValidatingTextBox()
{
InitializeComponent();
}
protected override void OnValidating(CancelEventArgs e)
{
bool bTest = txtRegExStringIsValid(this.Text.ToString());
ToolTip tip = new ToolTip();
if (bTest == false)
{
tip.Show("Only A-I", this, 2000);
this.Text = " ";
}
}
private bool txtRegExStringIsValid(string textToValidate)
{
// Exactly the same validation logic as in the same method on the form
}
}