爲了解決這個問題考慮訪問這些事實:
字典編輯表單
在這個例子中,我創建了一個表單編輯字典。請注意這幾點:
- 我創建從字典中的
DataTable
,然後設置DatTable
爲DataGridView
DataSource
,最後放物品回字典。
- 我設置了
Key
列作爲PrimaryKey
的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
一個實例,並把字典給它的構造,那麼你可以編輯字典usnig它。
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
這是Web窗體?還是Windows窗體?你應該永遠清楚你使用的框架是通過適當地標記你的問題。 – mason
感謝您的建議。會相應更新。 –
[顯示可編輯字典的最簡單方法是什麼]可能的重複(http://stackoverflow.com/questions/2798933/what-is-the-easiest-way-to-display-an-editable-dictionary) – Fabio