我有一个表单,上面有大约 20 个控件(ComboBox
、TextBox
等),我已预先加载了数据。这将显示给用户并使他们能够更改任何字段。
我不知道认识到变化已经发生的最佳方式。经过一番研究,我发现 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/