vb.net - 检查表单中的选择/文本是否已更改

标签 vb.net controls textchanged dirty-data

我有一个表单,上面有大约 20 个控件(ComboBoxTextBox 等),我已预先加载了数据。这将显示给用户并使他们能够更改任何字段。

我不知道认识到变化已经发生的最佳方式。经过一番研究,我发现 TextBox.TextChanged 并设置了 IsDirty = True 标志或类似的内容。

我认为这不会是 100% 防弹的,因为用户可能会更改该值,然后返回并将其更改为最初加载时的状态。我一直在考虑将当前数据保存到 .Tag 中,然后将其与用户单击“取消”时输入的 .Text 进行比较,以简单地询问他们是否他们想要保存更改。

这是我的代码:

Private Sub Form1_Load(ByVal sender as Object, byVal e as System.EventArgs)Handles MyBase.Load
    For Each ctr as Control in me.Controls
       if typeof ctr is TextBox then
         ctr.tag=ctr.text
       end if
    Next 
End Sub

这是用户单击“取消”时的代码:

Private Sub CmdCancel_Click (ByVal sender as Object, ByVal e As System.EventArgs) Handles CmdCancel.Click
    For each ctr As Control in Me.Controls
        If Typeof ctr is Textbox then
           if ctr.tag.tostring <> ctr.text then
               MsgBox ("Do you want to save the items", YesNo)
           end if
        End if
    Next
End sub

这是一种有效的方法吗?可以依靠吗?如果有人有更好的想法,我很想听听。

最佳答案

看看这个:

For Each txtBox In Me.Controls.OfType(Of TextBox)()
    If txtBox.Modified Then
        'Show message
    End If
Next

编辑

看看这个。如果您想要 .Tag 属性的替代方法,您可能会对以下内容感兴趣:

'Declare a dictionary to store your original values
Private _textboxDictionary As New Dictionary(Of TextBox, String)

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    'You would place this bit of code after you had set the values of the textboxes
    For Each txtBox In Me.Controls.OfType(Of TextBox)()
        _textboxDictionary.Add(txtBox, txtBox.Text)
    Next

End Sub

然后用它找出原始值并与新值进行比较:

For Each txtBox In Me.Controls.OfType(Of TextBox)()
    If txtBox.Modified Then
         Dim oldValue = (From kp As KeyValuePair(Of TextBox, String) In _textboxDictionary
                         Where kp.Key Is txtBox
                         Select kp.Value).First()
         If oldValue.ToString() <> txtBox.Text Then
             'Show message
         End If

    End If
Next

关于vb.net - 检查表单中的选择/文本是否已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40286380/

相关文章:

vb.net - 通过 XML-RPC 为 WordPress 帖子设置特色图片

VB.NET: 'friend' 修饰符有什么作用?

c# - 在 winforms 中创建动态 UI

c# - WPF UI 控件背景更改

c - 有人能解释一下这在 C/UNIX 中的作用吗

C#串口-不是所有的数据都添加到Listview

c# - 当 Visible = False 时,TextBox TextChanged 事件不会触发?

c# - 为什么 Split from System.String 不接受字符串作为重载?

.net - 在 Linq to SQL 中设置外键