2014-11-14 66 views
-1

其中包含的CheckBoxList作爲如何使編程選擇複選框?

 <asp:CheckBoxList ID="chklLineOfAuthority" RepeatColumns="3" RepeatLayout="Table" 
     RepeatDirection="Horizontal" AutoPostBack="false" CausesValidation="false" runat="server"> 
    </asp:CheckBoxList> 

在其ascx.cs文件我已經創建自定義的控制有一個像

public void FillLineOfAuthorityForProduct(string loastring) 
    { 
     //let's us consider loastring contains 

     string loastring = "Casualty, Credit, Motor Club"; 
     DataSet ds = new DataSet(); 
     LineOfAuthorityBL bl = new LineOfAuthorityBL(SessionContext.SystemUser); 
     bl.FetchAll(ds); 
     chklLineOfAuthority.DataSource = ds.Tables[bl.SqlEntityX]; 
     chklLineOfAuthority.DataTextField = "LineOfAuthorityX"; 
     chklLineOfAuthority.DataBind(); 
     ds = null; 
     bl = null; 

     string[] arrGroup = loastring.Split(','); 

      foreach (object obj in arrGroup) 
      { 

       for (int i = 0; i < chklLineOfAuthority.Items.Count; i++) 
       { 
        if (chklLineOfAuthority.Items[i].Value == obj.ToString()) 
        { 
         chklLineOfAuthority.Items[i].Selected = true; 
        } 
       } 

      } 
     } 

一個函數,則輸出應該像

enter image description here

我的意思是傷亡,汽車俱樂部,信用複選框應該被檢查。上面的代碼不起作用。

+1

你。將字符串拆分爲「,」s,並且空格可以包含在字符串部分中。您確定for循環中的if語句是否爲真值? –

+0

在你的'foreach'中設置一個斷點並檢查'obj'的值。 – CodeCaster

+0

您能否比較兩個問題......兩者是完全不同的...... – Nida

回答

0

通過CheckboxList使用foreach循環來,然後用obj.ToString()(比較每個ListItem值這將取代你的for循環類似下面:

foreach (ListItem itm in chklLineOfAuthority.Items) 
{ 
    if (itm.Value == obj.ToString()) 
    { 
     itm.Selected = true; 
    } 
} 
+0

它正確比較所有字符串。但是複選框未被選中 – Nida

+0

我可以在代碼中看到兩件事情:首先,您的字符串loastring是「Casualty,Credit,Motor Club」將其更改爲字符串「Casualty,Credit,Motor Club」,即逗號後刪除空格。二,因爲arrGroup已經被聲明爲一個字符串數組,所以將foreach(arrGroup中的object obj)更改爲'foreach(arrGroup中的字符串str)'。這仍然可能無法解決您的問題,但至少代碼是正確的。 – NP3

0

嘗試這個

foreach (object obj in arrGroup) 
{     
    chklLineOfAuthority.Items.FindByText(obj.ToString()).Selected = true; 
}