2011-12-25 85 views
1

我有一個checkboxlist,我想檢查它的一些項目, 項目,我想檢查存儲在數據庫中,我從數據庫中選擇它們,並在一個循環中,我寫了thees,但只選擇最後一項:((:如何檢查checkboxlist中的項目?

var selectedRoles = (from r in DataContext.Context.Core_PagesPermission 
        where r.PageName.Contains(pageName) select r) 
         .FirstOrDefault(); 
if(selectedRoles != null) 
{ 
    string roles = selectedRoles.Roles; 
    string[] role = roles.Split(','); 
    int countTags = role.Count(); 
    foreach (string word in role) 
    { 
     CheckBoxList1.SelectedValue = word; 
     Response.Write(word + "<br/>"); 
     countTags -= 1; 
    } 
} 

這工作:

var selectedRoles = (from r in DataContext.Context.Core_PagesPermission where r.PageName.Contains(pageName) select r) 
          .FirstOrDefault(); 
         dsRoles.DataBind(); 
         CheckBoxList1.DataBind(); 
         if(selectedRoles != null) 
         { 
         string roles = selectedRoles.Roles; 
         string[] role = roles.Split(','); 
         foreach (string word in role) 
         { 
          try 
          { 
           CheckBoxList1.Items.FindByValue(word).Selected = true; 
          } 
          catch (Exception exp) 
          { 
           lbError.Text= exp.ToString(); 
          } 
+0

你能不能請你的問題更精確。我是否正確的假設:你有一個顯示所有權限的複選框列表,你想檢查數據庫中的權限存儲? – 2011-12-25 17:05:49

+0

對不起,我的純英文 – 2011-12-25 17:15:29

回答

2

你將要選擇的單個項目:

CheckBoxList1.Items.FindByText(word).Selected = true; 

CheckBoxList1.Items.FindByValue(word).Selected = true; 

但是,如果checkboxlist沒有您正在查找的文本/值,它會引發錯誤。

+0

我得到了錯誤:(但我有所有項目 – 2011-12-25 17:43:19

+0

你也可以循環遍歷整個列表,並對列表中的每個單詞進行比較,然後選擇複選框。 I = 0; I 2011-12-26 06:24:27

0

數據表方法的CheckBoxList

for (int i = 0; i < dt.Rows.Count; i++) 
{ 
    chkCategories.Items.FindByValue(dt.Rows[i]["CategoryID"].ToString()).Selected = true; 
} 
相關問題