I have a TextBox
where the user can add and remove text, however each char relates to a row on a DataGridView, with a variety of user-selectable options. So knowing what char is being removed is very important because the DataGridView needs to know what row must be removed.
At first, I had a simple string-compare method, but with duplicate char sequences (ei "aaaa") it couldn't figure out which letter was removed and defaulted to returning the index of last char in the sequence. So I went online to see if there was a way to track the text caret's position, and there is...but not for WinForms. The only aspects I found for the Caret was SelectionStart
, SelectionLength
and SelectionText
; which will be usefully for batch remove, but not when the user hits the backbutton/deletebutton.
I'm pretty stumped right now. The "easiest" solution is switching to XAML because it tracks the Caret Position... but that feels like quiter talk. Though with that said, I still have no idea how to tackle this problem... any suggestions? (─‿‿─;;)
You can try to define the variable originalText
to save origianl textbox text and textlength
to save text length.
Subscribe to textBox1_Enter
to give them the initial value.
private void textBox1_Enter(object sender, EventArgs e)
{
textlength = textBox1.Text.Length;
originalText = textBox1.Text;
}
Then subscribe to textBox1_TextChanged
to get the deleted chars
.
int textlength;
string originalText;
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textlength > textBox1.Text.Length)
{
Console.WriteLine($"You deleted the char from {textBox1.SelectionStart} to {textBox1.SelectionStart + textlength - textBox1.Text.Length - 1}");
Console.WriteLine($"deleted substring {originalText.Substring(textBox1.SelectionStart, textlength - textBox1.Text.Length)}");
}
// reset
textlength = textBox1.Text.Length;
originalText = textBox1.Text;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.