2014-01-06 54 views
0

我的表單上有10 checkboxes。它們被命名爲checkBox1,checkBox2,...,checkBox10。 目前我的代碼看起來是這樣的:C#多選複選框

if(checkBox1.Checked) 
    Call MyFunction(1); 
if(checkBox2.Checked) 
    Call MyFunction(2); 


因爲我傳遞給我的函數的參數是一樣的checkbox號碼,我想用一個for循環,使每個checkbox_i ,我應該叫MyFunction(i)

感謝, 尼克

回答

2

不是很安全,但簡單的方法:

int index = 1; 
foreach (var checkBox in this.Controls.OfType<CheckBox>()) 
{ 
    if (checkBox.Checked) 
    { 
     MyFunction(index); 
    } 

    index++; 
} 

接下來的想法是安全的,但不是很優雅:

foreach (var checkBox in this.Controls.OfType<CheckBox>()) 
{ 
    if (checkBox.Checked) 
    { 
     int index = int.Parse(checkBox.Name.Substring(8)); 
     MyFunction(index); 
    } 
} 

歸根結底,最好是填充適當的索引所有的複選框的.Tag財產。在這個解決方案,你甚至可以跳過一些複選框是這樣的:

foreach (var checkBox in this.Controls.OfType<CheckBox>().Where(c => c.Checked)) 
{ 
    int? index = checkBox.Tag as int; 

    if (index.HasValue) 
    { 
     MyFunction(index.Value); 
    } 
} 

而且更易讀的方式將有複選框你有興趣在這個過程中您的窗體的構造例如列表:

relevantCheckBoxes = new List<CheckBox>(); 
relevantCheckBoxes.Add(this.checkBox1); 
relevantCheckBoxes.Add(this.checkBox3); 
// etc. 

然後:

for (int index = 0;index < relevantCheckboxes.Count;++index) 
{ 
    if (relevantCheckboxes[index].Checked) 
    { 
     MyFunction(index); 
    } 
} 
+0

如果'Form'有第11個checkBox,'MyFunction(int)'假定不會調用? –

+0

非常感謝Bartosz。我接近你介紹的解決方案之一,但你的更優雅。最後我選擇了你的第二個樣本。我不得不將代碼更改爲int index = int.Parse(checkBox.Name.Remove(0,8));因爲它給出了一個錯誤。 –

+0

@Nick_F好點 - 它應該是'8' :) – BartoszKP

1

確定有任何控件名稱名稱屬性檢查這個pesodo代碼

Checkbox t=CheckBox(object); 
var number=t.name.substring("checkbox".length,name.length-"checkbox".length) // to get only number or you can split name by regular expression 

myfunction(int.parse(number)); 
// try this code and and ask here agine if any problem due to I can't test it now