AlbA
AlbA

Reputation: 81

Selecting/Highlighting certain text in textbox

So I have a textbox with a time in it, which looks like this;

enter image description here

When you click in the textbox, and you click on the hour part, like this;

enter image description here

It should look like this;

enter image description here

Same goes for minutes, so when you are at the minute part of the textbox like this;

enter image description here

It should look like this then;

enter image description here

Basically what I am trying to do is make the program select/highlight the time for you. Depending on what you've clicked on.

What I have tried so far is this;

What should happen when you "select" the hour part:

textBox1.SelectionStart = 0; // The start of the selection
   textBox1.SelectionLength = 2; //Untill the ":" which seperates the hours from minutes

This works, the text will be selected like the thirth picture.

And this part:

textBox1.SelectionStart = 3; // The start of the selection, in this case after the ":"
       textBox1.SelectionLength = textBox1.Text.Length; //Untill the end

I know that you should be able to write a simple if-statement for this.

But my problem is, how can I check which part the "cursor" is at, in the textbox?

Upvotes: 1

Views: 81

Answers (1)

Shqiptar_Programmer
Shqiptar_Programmer

Reputation: 487

With selection start you can know where your cursor is at in the textbox.

private void textBox1_MouseClick(object sender, MouseEventArgs e)
            {
                if (textBox1.SelectionStart < 3)
                {
                    textBox1.SelectionStart = 0;
                    textBox1.SelectionLength = 2;
                }
                else if (textBox1.SelectionStart > 2)
                {
                    textBox1.SelectionStart = 3;
                    textBox1.SelectionLength = textBox1.Text.Length;
                }
            }

If an if-statement is true, I will select a certain text, so for example if your SelectionStart is 0, which means it is at the beginning of the textbox, the first 2 digits will be highlighted.

It should work with those 2 if-statements.

Upvotes: 1

Related Questions