user481758
user481758

Reputation:

Get last 3 characters during user typing

I need get last three character from richTextBox during when the user writes some text in richTextbox.

I bind property on Text property of richTextBox from Extended WPF toolkit.

public string RtbText
{
    get { return _rtbText; }
    set
    {
        _rtbText = value;
        NotifyPropertyChanged("RtbText");
    }
}

I use Reactive Extensions for .NET (Rx) and make Observer on property RtbText

    Observable.FromEvent<PropertyChangedEventArgs>(this, "PropertyChanged")
        .Where(e => e.EventArgs.PropertyName == "RtbText")
        .Select(_ => this.RtbText)
        .Where(text => text.Length > 1)
        .Do(AddSmiles)
        .Throttle(TimeSpan.FromSeconds(1))
        .Subscribe(GetLastThreeChars);

   private void GetLastThreeChars(string text)
   {
       if (text.Length > 3)
       {
           string lastThreeChars = text.Substring(text.Length - 2, text.Length);
       }
   }

But if I start typing in richTextBox I get this exception:

Index and length must refer to a location within the string.
Parameter name: length

at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)
at System.String.Substring(Int32 startIndex, Int32 length)
at WpfApplication1.MainWindow.GetLastThreeChars(String text) in C:\Users\Jan\Documents\Visual Studio 2010\Projects\C#\Pokec_Messenger\ver.beta\IoC.Get\Pokec_Messenger\ver.beta\Pokec_Messenger\WpfApplication1\MainWindow.xaml.cs:line 97
at System.Linq.Observable.<>c
_DisplayClass389`1.<>c_DisplayClass38b.b_388(TSource x)

Upvotes: 1

Views: 1115

Answers (2)

ChrisF
ChrisF

Reputation: 137128

If text.Length > 3 (say it's 4) then:

text.Length - 2 = 2

So you're code is:

string lastThreeChars = text.Substring(2, 4);

This will fail as you are asking for four characters in the substring, which puts it out of range.

String.Substring Method (Int32, Int32)

Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

Additionally your test and starting position are incorrect. Don't forget that C# arrays and strings are zero indexed. Checking for the case of length strictly greater than 3 you'll miss the case when the user has entered exactly three characters when you want to return the entire string.

Your code needs to be:

if (text.Length > 2)
{
    string lastThreeChars = text.Substring(text.Length - 3, 3);
}

If fact you don't need to specify the length:

if (text.Length > 2)
{
    string lastThreeChars = text.Substring(text.Length - 3);
}

will return the last three characters in the string.

Upvotes: 2

Kurru
Kurru

Reputation: 14321

This is another form. Which gets all the characters from some start position up to the end

string lastThreeChars = text.Substring(text.Length - 3);

maybe text.Length - 2. Untested

Upvotes: 1

Related Questions