2011-12-25 51 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; 
} 
相关问题