views:

3161

answers:

6

I have a standard WinForms TextBox and I want to insert text at the cursor's position in the text. How can I get the cursor's position?

Thanks

A: 

You want to check the SelectionStart property of the TextBox.

David Morton
+4  A: 

Regardless of whether any text is selected, the SelectionStart property represents the index into the text where you caret sits. So you can use String.Insert to inject some text, like this:

myTextBox.Text.Insert(myTextBox.SelectionStart, "Hello world");
Matt Hamilton
A: 

Hi both,

Thanks for that, I have a small problem as soon as I click my button to insert the text it fails as the cursor is no longer in the textbox. How can I make it stick?

Thanks

James,Use the comment feature, or update your original question, rather than posting replies. They just pollute the page for other folks looking for the same answer.
Matt Hamilton
+1  A: 

Your gonna have to keep the selectionstart property in a variable, and then when you press the button, shift the focus back to the textbox. Then set the selectionstart property tot he one in the variable.

masfenix
A: 

On what event would you suggest I record the variable? Leave?

Currently I have:

private void comboBoxWildCard_SelectedIndexChanged(object sender, EventArgs e)
{
    textBoxSt1.Focus();
    textBoxSt1.Text.Insert(intCursorPos, comboBoxWildCard.SelectedItem.ToString());

}

private void textBoxSt1_Leave(object sender, EventArgs e)
{
    intCursorPos = textBoxSt1.SelectionStart;
}

Recording on the Leave event is working but the text doesn't get inserted, am I missing something?

UPDATE: I needed textBoxSt1.Text =

textBoxSt1.Text = textBoxSt1.Text.Insert(intCursorPos, comboBoxWildCard.SelectedItem.ToString());

Thanks all.

Thanks

A: 

James, it's pretty inefficient that you need to replace the whole string when you only want to insert some text at the cursor position.

A better solution would be:

textBoxSt1.SelectedText = ComboBoxWildCard.SelectedItem.ToString();

When you have nothing selected, that will insert the new text at the cursor position. If you have something selected, this will replace your selected text with the text you want to insert.

I found this solution from the eggheadcafe site.

MaDDoG