2009-07-28 74 views
3

我有一個ListViewEditItemTemplate調用方法onItemEditingListView包含CheckBoxList - 選擇的項目不顯示爲檢查

在我的ListView我有一個CheckBoxList綁定使用LINQ

在我的onItemEditing方法中,我試圖檢查某些CheckBoxes,如果它們出現在鏈接用戶與扇區的查找表中。

然而,當我加載EditItemTemplate沒有CheckBoxes,儘管我已經將它們設置爲在onItemEditing方法選擇被選中。

這裏的方法:

protected void onItemEditing(object sender, ListViewEditEventArgs e) 
{ 
    ListView1.EditIndex = e.NewEditIndex; 
    ListView1.DataBind(); 

    int regId = Convert.ToInt32(((Label)ListView1.Items[e.NewEditIndex].FindControl("LblRegId")).Text); 
    CheckBoxList cbl = (CheckBoxList) ListView1.Items[e.NewEditIndex].FindControl("chkLstSectors"); 

//test to see if forcing first check box to be selected works - doesn't work 
    cbl.Items[0].Selected = true; 

    SqlConnection objConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DaresburyConnectionString"].ToString()); 
    SqlCommand objCmd = new SqlCommand("select * from register_sectors where register_id= " + regId, objConn); 
    objConn.Open(); 

    SqlDataReader objReader = objCmd.ExecuteReader(); 

    if (objReader != null) 
    { 
     while (objReader.Read()) 
     { 
      ListItem currentCheckBox = cbl.Items.FindByValue(objReader["sector_id"].ToString()); 
      if (currentCheckBox != null) 
      { 
       currentCheckBox.Selected = true; 
      } 
     } 
    } 
} 

任何想法如何解決這個問題?

+0

你在哪裏創建控件?在加載時,在init? – 2009-07-30 03:46:42

回答

1

問題是listView綁定checkboxlist後被綁定了。

我刪除了綁定,它的工作原理!

0

我希望我不是我的回答爲時已晚;)

我在數據綁定應該像其他控件一個ListView一個CheckBoxList的。在數據庫中的值是從該枚舉的計算值:

public enum SiteType 
{ 
    Owner = 1, 
    Reseller = 2, 
    SubReseller = 4, 
    Distributor = 8 
    Manufacturer = 16, 
    Consumer = 32 
} 

如果該值爲24,這意味着分發服務器和生產者(8 + 16)。

我添加了一個HiddenField到EditItem在我的ListView數據綁定的值:

<EditItemTemplate> 
    <tr> 
     <td> 
      <asp:CheckBoxList ID="cblSiteTypes" runat="server" RepeatLayout="Flow" 
       DataSourceID="ObjectDataSource4" DataTextField="Key" DataValueField="Value" /> 
      <asp:HiddenField ID="hfSiteTypes" runat="server" Value='<%# Bind("SiteType") %>' OnDataBinding="hfSiteTypesBnd" /> 
     </td> 
    </tr> 
    <!-- other data... --> 
</EditItemTemplate> 

的的CheckBoxList通過另一個數據源,它返回與來自枚舉數據Dictionary對象填補。在後面的代碼中,我使用HiddenField的OnDataBinding方法進行選擇:

protected void hfSiteTypesBnd(object sender, EventArgs e) 
{ 
    // read the value 
    HiddenField hf = (HiddenField)sender; 
    short val = Convert.ToInt16(hf.Value); 
    // find the checkboxlist 
    CheckBoxList cblSiteTypes = (CheckBoxList)hf.Parent.FindControl("cblSiteTypes"); 
    // clear the selection (may be not needed) 
    cblSiteTypes.ClearSelection(); 
    // for each item 
    foreach (ListItem li in cblSiteTypes.Items) 
    { 
     // get the value from each item and... 
     short v = Convert.ToInt16(li.Value); 
     // ...look up whether this value is matching or not 
     if ((val & v) == v) li.Selected = true; 
    } 
} 

etvoilà!