2011-10-28 42 views
0

我已經把我所有的表單控件的一個哈希表從而得到一個值: -如何從哈希表條目

foreach (Control c in this.Controls) 
     { 
      myhash.Add(c.Name, c); 

     } 

這當中有兩個單選按鈕。我想獲得按鈕的值,即選中或取消選中,並將它們分配給一個變量。我該怎麼做,請。感謝所有幫助。

回答

3
foreach (Control c in hashtable.Values) 
{ 
    if(c is RadioButton) 
    { 
     string name = x.Name; 
     bool isChecked = (c as RadioButton).Checked; 
    } 
} 

,或者如果你知道這個名字

(hashtable["name"] as RadioButton).Checked; 
+0

太棒了!謝謝。只是我希望的那種簡單而直接的答案。 – user995689

0

將單選按鈕的控件投射到實例,然後查看the checked property。至少這是我在WebForms中使用類似的類多次完成的。

2

你可以通過與它相關的密鑰檢索值,基本上控制名稱是在哈希表中的鍵,你所創建。所以,如果你知道控件的名稱,你需要訪問:

var control = hash[radioButtonControlName] as RadioButton; 

否則使用LINQ OfType()List.ForEach()

// OfType() does check whether each item in hash.Values is of RadioButton type 
// and return only matchings 
hash.Values.OfType<RadioButton>() 
      .ToList() 
      .ForEach(rb => { bool isChecked = rb.Checked }); 

或使用foreach循環: (there is a nice overview of misconception of the List.ForEach() usage

var radioButtons = hash.Values.OfType<RadioButton>(); 

foreach(var button in radioButons) 
{ 
    bool isChecked = rb.Checked; 
} 
0

假設代碼中的散列表是Hashtable的一個實例:

Hashtable myhash= new Hashtable(); 
foreach (Control c in this.Controls) 
{ 
    myhash.Add(c.Name, c); 
} 

你可以這樣做:

foreach (DictionaryEntry entry in myhash) 
{ 
    RadioButton rb = entry.Value as RadioButton; 
    if (rb != null) 
     bool checked = rb.Checked; 
} 

還可以看到與HashMap中條目的關鍵:

foreach (DictionaryEntry entry in myhash) 
{ 
    var componentName = entry.Key; 
} 

這將是你把組件的名稱對應hashmap(c.Name)。

希望這對你有所幫助。