[英]C# - TextBox_TextChanged event - revert to previous value
我將在TextBox_TextChanged事件上發布一個確認對話框。 如果用戶單擊“否”,則我想以某種方式將文本框還原為其舊值(即在更改之前),但是在觸發事件時,TextBox.Text已經是更改后的值...是有沒有辦法保存或獲得舊的價值?
贊賞任何想法或方法。 謝謝!
這是我的代碼:
private void txtFCServerURL_TextChanged(object sender, EventArgs e)
{
DialogResult clearGrid = MessageBox.Show("Changing the text will clear the grid. Are you sure?", "Confirmation", MessageBoxButtons.YesNo);
if (clearGrid == DialogResult.Yes)
{
for (int i = 0; i < dgvGrid.Rows.Count; i++)
{
dgvGrid.Rows.RemoveAt(0);
}
}
else txtFCServerURL.Text = [TEXT BEFORE CHANGE]
}
選項1:一個文本框有一個Undo
方法。 這是一個帶有代碼示例的鏈接:
http://msdn.microsoft.com/zh-cn/library/system.windows.forms.textboxbase.undo%28v=vs.110%29.aspx
為了簡化起見,這是鏈接中的示例:
private void Menu_Copy(System.Object sender, System.EventArgs e)
{
// Ensure that text is selected in the text box.
if(textBox1.SelectionLength > 0)
// Copy the selected text to the Clipboard.
textBox1.Copy();
}
private void Menu_Cut(System.Object sender, System.EventArgs e)
{
// Ensure that text is currently selected in the text box.
if(textBox1.SelectedText != "")
// Cut the selected text in the control and paste it into the Clipboard.
textBox1.Cut();
}
private void Menu_Paste(System.Object sender, System.EventArgs e)
{
// Determine if there is any text in the Clipboard to paste into the text box.
if(Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{
// Determine if any text is selected in the text box.
if(textBox1.SelectionLength > 0)
{
// Ask user if they want to paste over currently selected text.
if(MessageBox.Show("Do you want to paste over current selection?", "Cut Example", MessageBoxButtons.YesNo) == DialogResult.No)
// Move selection to the point after the current selection and paste.
textBox1.SelectionStart = textBox1.SelectionStart + textBox1.SelectionLength;
}
// Paste current text in Clipboard into text box.
textBox1.Paste();
}
}
private void Menu_Undo(System.Object sender, System.EventArgs e)
{
// Determine if last operation can be undone in text box.
if(textBox1.CanUndo == true)
{
// Undo the last operation.
textBox1.Undo();
// Clear the undo buffer to prevent last action from being redone.
textBox1.ClearUndo();
}
}
選項2:如果只需要最后一個文本(意味着僅向后退一步),則可以使用文本更改事件在更改之前用當前文本更新字符串變量,然后可以在任何需要的地方使用它。
我會做的(不確定是否是最好的選擇)是做一個變量並在TextChanged的末尾設置其值。 這樣,下一次它將進入TextChanged時,您仍將具有先前更改的值。
string txt = "";
private void txtFCServerURL_TextChanged(object sender, EventArgs e)
{
if(txtFCServerURL.Text != txt)
{
DialogResult clearGrid = MessageBox.Show("Changing the text will clear the grid. Are you sure?", "Confirmation", MessageBoxButtons.YesNo);
if (clearGrid == DialogResult.Yes)
{
for (int i = 0; i < dgvGrid.Rows.Count; i++)
{
dgvGrid.Rows.RemoveAt(0);
}
}
else txtFCServerURL.Text = txt;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.