Repeater 内嵌 CheckBoxList 的同时绑定

时间:2022-01-08 10:13:15

Repeater 内嵌 CheckBoxList 显示年级及其下班级列表

页面HTML部分
-------------
<tr>
 <td>年级班级列表:</td>
 <td>
 <asp:Repeater ID="repeater_GradeClass" runat="server" >
   <ItemTemplate>
      <table>
         <tr>
            <td>
              <asp:Label ID="lbl_Grade" runat="server" style="color:Red;"
                   Text='<%# Eval("GradeName") %>'></asp:Label>
            </td>
         </tr>
         <tr>
            <td>
              <asp:CheckBoxList ID="chklist_Classes" runat="server" RepeatDirection="horizontal"                                                  DataSource='<%# GetClassesByGradeID(Convert.ToString(Eval("GradeID"))) %>'
                  DataTextField='<%# GetClassesByGradeID(Convert.ToString(Eval("GradeID"))).Columns["ClassName"].ToString() %>'
                  DataValueField='<%# GetClassesByGradeID(Convert.ToString(Eval("GradeID"))).Columns["ClassID"].ToString()  %>'
              >
              </asp:CheckBoxList>
            </td>
          </tr>
       </table>
    </ItemTemplate>
 </asp:Repeater>
 </td>
</tr>

页面cs部分
------------
    #region 绑定年级信息 可在Page_Load时 调用该方法 进行页面绑定
    private void BindRepeaterGateway()
    {
        //...相关数据库访问省略
        DataSet ds = GetDataSetGrade();//两个字段 GradeID,GradeName
        if ((ds != null) && (ds.Tables[0].Rows.Count > 0))
        {
            DataSet ds1 = GetDataSetClass();//三个字段 GradeID,ClassID,ClassName
            ViewState.Add("dsClass", ds1);

            this.repeater_GradeClass.DataSource = ds.Tables[0];
            this.repeater_GradeClass.DataBind();
           
        } 
    }
    #endregion

    #region 根据年级GradeID 得到其下的班级Class
    protected DataTable GetRegItemsByGatewayID(string strGradeID)
    {
        if (ViewState["dsClass"] != null)
        {
            DataView dv = ((DataSet)ViewState["dsClass"]).Tables[0].DefaultView;
            dv.RowFilter = " GradeID = "+strGradeID+" ";
            DataTable dt = dv.ToTable();
            return dt;
        }
        else
        {
            return null;
        }
    }
    #endregion


       //取得选中的年级值
        string items = "";
        for (int i = 0; i < this.repeater_GradeClass.Items.Count; i++)
        {
            CheckBoxList chklist = (CheckBoxList)this.repeater_GradeClass.Items[i].FindControl("chklist_Classes");
            for (int j = 0; j < chklist.Items.Count; j++)
            {
                if (chklist.Items[j].Selected)
                    items += "," + chklist.Items[j].Value;
            }
        }
        if (items.Length > 0)
            items = items.Substring(1);