2013-04-04 35 views
2

我试图从checkboxlist中获取多个值并将它们添加到列表中,但即使列表包含适当的计数值,但检查值始终为false。CheckBoxList'.Selected'在每种情况下都返回false

代码来填充:

Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey; 
HelpingOthersEntities helpData = new HelpingOthersEntities(); 
List<LookupStoreLocationsByUserName> theDataSet = helpData.LookupStoreLocationsByUserName(userGuid).ToList<LookupStoreLocationsByUserName>(); 
locCkBox.DataSource = theDataSet; 
locCkBox.DataTextField = "slAddress"; 
locCkBox.DataValueField = "storeLocationID"; 
locCkBox.DataBind(); 

代码添加到列表:

List<int> locList = new List<int>(); 

for (int x = 0; x < locCkBox.Items.Count; x++){ 
    if(locCkBox.Items[x].Selected){ 
     locList.Add(int.Parse(locCkBox.Items[x].Value)); 
    } 
} 

我遇到的问题是,我无法进入items.selected 我值始终为false。

我已经尝试从回发中填充复选框,但我得到了相同的结果。我的清单给了我适当的.Count数量的值,但items.selected = false?

我已经尝试了一个foreach循环来添加到列表中,但我一遍又一遍地得到相同的结果。我错过了一个事件或什么?

回答

7

我打算在这里做一个猜测,并说你的代码不会在页面加载事件中被调用,所以你有如下的东西。

private void Page_Load() 
{ 
    Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey; 
    HelpingOthersEntities helpData = new HelpingOthersEntities(); 
    List<LookupStoreLocationsByUserName> theDataSet = helpData.LookupStoreLocationsByUserName(userGuid).ToList<LookupStoreLocationsByUserName>(); 
    locCkBox.DataSource = theDataSet; 
    locCkBox.DataTextField = "slAddress"; 
    locCkBox.DataValueField = "storeLocationID"; 
    locCkBox.DataBind(); 
} 

如果是这样的话,那么你有效地写在每个请求的回发数据。要排序了这一点,你只需要进行数据绑定时,它不是一个回传,所以你需要上面的代码更改为

private void Page_Load() 
{ 
    if (!IsPostBack) 
    { 
     Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey; 
     HelpingOthersEntities helpData = new HelpingOthersEntities(); 
     List<LookupStoreLocationsByUserName> theDataSet = helpData.LookupStoreLocationsByUserName(userGuid).ToList<LookupStoreLocationsByUserName>(); 
     locCkBox.DataSource = theDataSet; 
     locCkBox.DataTextField = "slAddress"; 
     locCkBox.DataValueField = "storeLocationID"; 
     locCkBox.DataBind(); 
    } 
} 

然后,您应该能够测试项目的Selected属性。我想也可能改变你的使用,以测试选定喜欢的东西

List<int> locList = new List<int>(); 
foreach(var item in locCkBox.Items) 
{ 
    if(item.Selected) 
    { 
    locList.Add(int.Parse(item.Value)); 
    } 
} 

,或者如果你的代码与上可用的LINQ NET版本

List<int> locList = new List<int>(); 
(from item in locCkBox.Items where item.Selected == true select item).ForEach(i => locList.Add(i.Value)); 
2

确保同时结合在checkboxlist页面加载你已经设置了这个检查。

if (!Page.IsPostBack) 
{ 
...bind your data 
} 

这应该是诀窍。

相关问题