(C#) 从 TextBox WinForms 的删除字符中获取索引
(C#) Getting the index from a remove char of a TextBox WinForms
我有一个 TextBox
,用户可以在其中添加和删除文本,但是每个字符都与 DataGridView 上的一行相关,具有多种用户可选选项。所以知道要删除的字符非常重要,因为 DataGridView 需要知道必须删除的行。
起初,我有一个简单的字符串比较方法,但是对于重复的字符序列 (e.i. "aaaa") 它无法确定删除了哪个字母并默认返回索引序列中的最后一个字符。所以我上网查看是否有一种方法可以跟踪文本插入符号的位置,并且有...但不适用于 WinForms。我发现插入符号的唯一方面是 SelectionStart
、SelectionLength
和 SelectionText
;这对于批量删除很有用,但当用户点击 backbutton/deletebutton.
时则不会
我现在很困惑。 “最简单”的解决方案是切换到 XAML 因为它跟踪插入符位置......但这感觉像是在说话。尽管如此,我仍然不知道如何解决这个问题。
您可以尝试定义变量 originalText
来保存原始文本框文本和 textlength
来保存文本长度。
订阅textBox1_Enter
给他们初始值
private void textBox1_Enter(object sender, EventArgs e)
{
textlength = textBox1.Text.Length;
originalText = textBox1.Text;
}
然后订阅textBox1_TextChanged
获得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;
}
我有一个 TextBox
,用户可以在其中添加和删除文本,但是每个字符都与 DataGridView 上的一行相关,具有多种用户可选选项。所以知道要删除的字符非常重要,因为 DataGridView 需要知道必须删除的行。
起初,我有一个简单的字符串比较方法,但是对于重复的字符序列 (e.i. "aaaa") 它无法确定删除了哪个字母并默认返回索引序列中的最后一个字符。所以我上网查看是否有一种方法可以跟踪文本插入符号的位置,并且有...但不适用于 WinForms。我发现插入符号的唯一方面是 SelectionStart
、SelectionLength
和 SelectionText
;这对于批量删除很有用,但当用户点击 backbutton/deletebutton.
我现在很困惑。 “最简单”的解决方案是切换到 XAML 因为它跟踪插入符位置......但这感觉像是在说话。尽管如此,我仍然不知道如何解决这个问题。
您可以尝试定义变量 originalText
来保存原始文本框文本和 textlength
来保存文本长度。
订阅textBox1_Enter
给他们初始值
private void textBox1_Enter(object sender, EventArgs e)
{
textlength = textBox1.Text.Length;
originalText = textBox1.Text;
}
然后订阅textBox1_TextChanged
获得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;
}