2012-10-20 48 views
1

即時創建我的應用程序功能,將重新創建CTRL + Z的事情。我有幾個textboxs和我做了一個表是這樣的:有問題HashTable的編譯錯誤(缺少強制轉換?)

hashtable textChanges[obj.Name, obj.Text] = new HashTable(50);

IM extractthe值從chossen關鍵。即使keyDown被解僱,我也得到了鑰匙。

事件即時尋找具有焦點的控制,並用自己的名字來提取最後一個值,他進入表。

這就是事件代碼:

這是怎麼我添加鍵&價值的哈希表

private void textBox_OnTextChange(object sender, EventArgs e) 
    { 
     if (sender.GetType() == typeof(TextBox)) 
     { 
      TextBox workingTextBox = (TextBox)sender; 
      textChanges.Add(workingTextBox.Name, workingTextBox.Text); 
     } 

     if (sender.GetType() == typeof(RichTextBox)) 
     { 
      RichTextBox workingRichTextBox = (RichTextBox)sender; 
      textChanges.Add(workingRichTextBox.Name, workingRichTextBox.Text); 
     } 
    } 

爲什麼我得到缺少強制錯誤?

(對不起,我的英語)

+6

你還在使用'HashTable'任何理由嗎?包括'字典<,>'在內的通用集合在7年前出現,使生活更加美好... –

+0

i thgohot泛型dosnt在XP上工作。我在工作嗎? – samy

+0

FYI - 兩個'TextBox'和'RichTextBox'也['TextBoxBase'](http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase(V = VS.100) .aspx),它具有'Name'和'Text'等屬性。 –

回答

3

您需要將其轉換爲字符串。如果你使用字典會更好。 Dictionary是一個泛型類型,你不需要hashtable所需的類型轉換。 Hashtable stores the object type and you are required to type cast the object back to your desired type

obj.Text = textChanges[obj.Name].ToString(); 
+0

但是,這不是obj.Name返回一個字符串? – samy

+0

哈希表存儲對象不是類型您更好地使用字典,http://stackoverflow.com/questions/301371/why-is-dictionary-preferred-over-hashtable – Adil

+0

喔,好,我現在就買下THX。當10mintus wair結束時,我會給你正確的答案。 – samy

2

是的,你需要類型轉換。

但考慮重構你的代碼。用戶generic dictionary而不是哈希表:

Dictionary<string, string> textChanges = new Dictionary<string, string>(50); 

而且使用LINQ檢索集中文本框:

private void Form1_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.Control && e.KeyData == Keys.Z) 
    { 
     foreach (var textBox in Controls.OfType<TextBox>().Where(x => x.Focused)) 
      textBox.Text = textChanges[textBox.Name]; 
    } 
}