要解决这个问题,请考虑以下事实:
字典编辑表格
在本例中,我创建了一个表单来编辑字典。请注意以下几点:
- 我从字典中创建了一个
DataTable,然后将DatTable 设置为DataGridView 的DataSource,最后将项目放回字典中。
- 我将
Key 列设置为 PrimaryKey of DataTable 以使密钥唯一。
- 我已处理
DataError 事件以在您输入无效密钥时显示错误
- 为了将项目放回字典,我首先尝试将项目添加到一个空字典,最后如果任务成功,我清除主字典并将项目放回字典。
示例源码如下:
Imports System.ComponentModel
Public Class DictionaryEditForm
Public Sub New(ByVal Dictionary As Dictionary(Of String, String))
InitializeComponent()
Me.Dictionary = Dictionary
End Sub
Public Property Dictionary() As Dictionary(Of String, String)
Dim Table As DataTable
Const Key As String = "Key"
Const Value As String = "Value"
Private Sub DictionaryEditForm_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Table = New DataTable()
Table.Columns.Add(Key, GetType(String))
Table.Columns.Add(Value, GetType(String))
Table.PrimaryKey = {Table.Columns(Key)}
For Each item In Dictionary
Table.Rows.Add(item.Key, item.Value)
Next
DataGridView1.DataSource = Table
End Sub
Private Sub SaveButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveButton.Click
Dim temp As New Dictionary(Of String, String)
For Each item As DataRow In Table.Rows
temp.Add(item.Field(Of String)(Key), item.Field(Of String)(Value))
Next
Dictionary.Clear()
For Each item In temp
Dictionary.Add(item.Key, item.Value)
Next
Me.DialogResult = DialogResult.OK
End Sub
Private Sub DataGridView1_DataError(ByVal sender As System.Object, _
ByVal e As DataGridViewDataErrorEventArgs) Handles DataGridView1.DataError
MessageBox.Show(e.Exception.Message)
e.Cancel = True
End Sub
End Class
用法
创建DictionaryEditForm 的实例并将字典传递给它的构造函数就足够了,然后您可以使用它来编辑字典。
Public Class MainForm
Private Sub EditDictionaryButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles EditDictionaryButton.Click
Dim Dictionary = New Dictionary(Of String, String) From
{{"1", "One"}, {"2", "Two"}, {"3", "Three"}}
Dim f = New DictionaryEditForm(Dictionary)
f.ShowDialog()
End Sub
End Class