Search specified string inside textbox

10,059

Solution 1

Here a sample pseudocode that can help you; (Put in your validating event)

int pos = textbox1.Text.IndexOf("YYMM");
if(pos != -1)
{ 
    textbox1.SelectionStart = pos;
    textbox1.SelectionLength = 4;
    // MessageBox("Error");
} 

Solution 2

This will assign the start index and the length of the selection, but it will not make it visible. To ensure visibility, I would recommend to add

textbox1.ScrollToCaret();
textbox1.HideSelection = false;
Share:
10,059
Elfoc
Author by

Elfoc

Updated on June 13, 2022

Comments

  • Elfoc
    Elfoc almost 2 years

    i have textbox with text:

    1234 YYMM 1057316895 12, AB 6386 ABC
    

    where YYMM is in this case Year and Month. What i'd like to do is to search if in this textbox exist YYMM, and highlight this part of text, or somehow show that in this specified textbox exist not fully completed field.

    So when i rewrite this string with 1203 instead of YYMM error will not be received.

    And! This YYMM can be in any place of string in textbox, so i can't do something like

    if (textbox1.Text.Substring(x,4)=="YYMM) {}
    

    where x is index of YYMM location.

    Tnx