2017-01-15 19 views
0

我想從CheckBoxList發送2種顏色,如藍色和紅色,這種方法需要4個可選參數並打印最終的組合結果。如何將CheckBoxList項目發送到方法?

這是CheckBoxList的:

Choose Two Colors: 
    <asp:CheckBoxList ID="CheckBoxList1" runat="server" OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged"> 
     <asp:ListItem>Red</asp:ListItem> 
     <asp:ListItem>Blue</asp:ListItem> 
     <asp:ListItem>Yellow</asp:ListItem> 
     <asp:ListItem>Green</asp:ListItem> 
    </asp:CheckBoxList> 

這是一個需要4個可選參數的方法:

static string ColorMixer(string Blue = "NotDefined", string Yellow = "NotDefined", string Red = "NotDefined", 
    string Green = "NotDefined") 
{ 

    string blue = Blue; 
    string yellow = Yellow; 
    string red = Red; 
    string green = Green; 
    string results; 
    if (blue.Equals("Blue")&&yellow.Equals("Yellow")) 
    { 
     results = "GREEN"; 
     return results; 
    } 
    if (red.Equals("Red")& green.Equals("Green")) 
    { 
     results = "Brown"; 
     return results; 
    } 

    the rest of codes goes here .... 

    else 
    { 
     results = "Result is Unspecified"; 
    } 
    return results; 
} 

現在,當有人從CheckBoxList的選擇兩種顏色我想拿到兩種色搭配類似代碼這個:

protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    foreach (ListItem item in CheckBoxList1.Items) 
    { 
     if (item.Selected) 
     { 

      string selectedoptions; 
      selectedoptions = item.Text; 
     } 

    } 

} 

然後發送選定的字符串項作爲命名參數方法

如何從字符串「selectedoptions」中獲取選定的顏色,然後將其格式化爲?

ColorMix(Blue:"Blue",Red:"Red") 

其中「藍」和「紅」是用戶選擇的顏色。

+0

請確認您的問題或您得到的錯誤! – Null

+0

只需要當有人從checkboxlist中選擇兩種顏色時,我就可以將項目作爲命名參數發送給方法。 – Mohsen

回答

0

這不是ASP.Net,但我很肯定同樣適用。我不認爲你正在爲你正在嘗試做的事情使用正確的事件。事件CheckBoxList1_SelectedIndexChanged發生,每次用戶點擊CheckBoxList並更改選擇哪個項目。即使複選框未被更改,事件也會觸發。當然,你可以做這裏需要做的事情,比如檢查哪些複選框被選中並將某些變量傳遞給方法,但是每當用戶更改選擇時,都會這樣做。

我猜測一個按鈕將是一個更好的控制來激發你的顏色方法。這樣你就不會循環直到按下這個按鈕。然後,您可以遍歷列表並獲取選中的顏色。如果只檢查一種顏色或者三種或更多顏色,則不清楚你想要做什麼,因爲該帖子表明你只想傳遞兩種顏色。

下面的代碼(c#code)是我用於CheckedListBox的代碼,其中項目被命名爲紅色,藍色,綠色和黃色。我用Button_Click事件而不是CheckBoxList1_SelectedIndexChanged事件。當按下按鈕時,它會簡單地遍歷列表並顯示項目索引,名稱及其檢查狀態。

private void button1_Click(object sender, EventArgs e) { 
    // Make a list of the checked colors you want to pass 
    //List<string> checkedItems = new List<string>(); 
    int index; 
    foreach (string item in checkedListBox1.Items) { 
    index = checkedListBox1.Items.IndexOf(item); 
    string checkState = checkedListBox1.GetItemCheckState(index).ToString(); 
    MessageBox.Show("Item on line " + index + " name: " + item + 
        " is currently: " + checkState); 
    } 
} 

希望這會有所幫助!

+0

非常感謝,這是非常好的方法 – Mohsen

相關問題