2015-09-28 32 views
1

我有一個ComboBoxList,其中包含某些項目和一個按鈕。點擊事件時,我想更改項目的文本顏色如果檢查(將文本顏色更改爲紅色或綠色)。但是如果項目顏色已經改變(變爲紅色或綠色)並且項目在第二輪中未被選中,則顏色應該恢復爲原始顏色。 以下是我試過的代碼片段。如何更改我的ComboBoxList中項目的顏色

ASPX

<body> 
    <form id="form1" 
      runat="server"> 
     <div> 
      <asp:checkboxlist runat="server" 
           EnableViewState="true" 
           id="cbl" /> 
      <asp:Button ID="Button1" 
         runat="server" 
         Text="Button" 
         OnClick="Button1_Click" /> 
     </div> 
    </form> 
</body> 

服務器側

protected void Button1_Click(object sender, EventArgs e) 
{ 
    for (int i =0; i< count; i++) 
    { 
     if (this.ColumnsList.Items(i).Selected) 
     { 
      this.ColumnsList.Items(i).Attributes.Add("style", "Color=Red;"); 
     } 
    } 
} 

錯誤消息是

非可調用部件 'System.Web.UI.WebControls.ListControl.Items' 不能使用li一種方法。

怎麼回事?

回答

0

使用ForEach代替For和嘗試下面的代碼。

foreach (ListItem item in this.ColumnsList.Items) 
{ 
    if (item.Selected) 
    { 
     item.Attributes.Add("style", "Color: Red"); 
    } 
} 
4

可能:

if (this.ColumnsList.Items[i].Selected) 
    { 
     this.ColumnsList.Items[i].Attributes.Add("style", "color: red;"); 
    } 
0

,你可以做這樣的......它正在測試很好..

protected void Button1_Click(object sender, EventArgs e) 
{ 
    for (int i = 0; i <CheckBoxList1.Items.Count; i++) 
    { 
     if (CheckBoxList1.Items[i].Selected) 
     { 
      CheckBoxList1.Items[i].Attributes.Add("style", "color:red"); 
     } 
    } 
} 
+0

這不會用於該用途的工作case ..因爲這隻適用於前三項..休息是什麼..這是不完整的答案.. –

+0

哦!...這只是一個例子...我認爲你可以解決for循環布爾值..這是你完整的答案......我有糾正了答案..請看看...... :) –

0

兩個問題在你的代碼。

  1. 而不是使用RoundBracket()使用SquareBraket []()在此情況下無法正常工作。

使用CheckBoxList1.Items[i].Selected代替CheckBoxList1.Items(I).Selected

  • 代替使用Add("style", "Color=Red;");添加顏色的,使用Add("style", "Color: Red");
  • 相關問題