-2

I have textBox and I want when I type @ the cursor automatically go to the begin of the textbox (like you pressed the Home Button on the keyboard) I tried this code

richTextBox1.Select(0, 0);

but it's not working as I want ( like when you press the home button on keyboard ) this is the all of the code

private void RichTextBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!Char.IsLetterOrDigit(e.KeyChar))
        {
            richTextBox1.Select(0, 0);
            checkLog = true;
        }
    }
milad
  • 43
  • 5
  • 3
    Your question actually requires a Javascript solution. It's therefore not a C# or ASP.NET question. – ProgrammingLlama Oct 06 '20 at 06:40
  • Are you sure you execute the code when you add the @ sign. Could you provide more code please? – IndieGameDev Oct 06 '20 at 06:40
  • @John you saying there is no way to solve this ? – milad Oct 06 '20 at 06:42
  • How exactly does it not work the way you want it to? What are you seeing, and what did you hope so see? Where have you placed this `Select()` call? Please [edit] into your question more code and more details. – Ken Y-N Oct 06 '20 at 06:43
  • 2
    No, I said your question is about Javascript as that's what is required for real-time interactive changes to your page. Web applications aren't like traditional desktop applications, so things like keypresses aren't streamed to the server. – ProgrammingLlama Oct 06 '20 at 06:43
  • So how does or doesn't this work? Have you placed a breakpoint and checked whether your code ends up in this method? – CodeCaster Oct 06 '20 at 07:02

2 Answers2

0

This does the work:

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    if(richTextBox1.Text.Contains('@'))
    {
        richTextBox1.Select(0, 0);
    }
}

KeyPress event actually happens before the character get added to the textbox so with KeyPress it actually goes to the beginning of the textbox and then adds the '@' there.

Hossein Ebrahimi
  • 632
  • 10
  • 20
0

TextChanged event and String.IndexOf will get the job done, String.Contains is another option for readability and it calls IndexOf internally Is String.Contains() faster than String.IndexOf()?

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    if (richTextBox1.Text.IndexOf("@") > -1)
    {
        richTextBox1.Select(0, 0);
    }
}
kshkarin
  • 574
  • 4
  • 9