2013-04-04 73 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 
} 

這應該是訣竅。

相關問題