DataList、Repeater、GridView中的Checkbox取值问题

时间:2023-01-21 14:26:14

先看页面代码

 <asp:DataList id="DataList1" runat="server" Width="100%" RepeatColumns="4" Font-Size="10pt">
<ItemTemplate>
<TABLE id="Table2" cellSpacing="0" cellPadding="0" width="100%" bgColor="gainsboro" border="0">
<TR>
<TD align="center">
<asp:Label id=lblOName runat="server" Font-Size="10pt" Text='<%# DataBinder.eval_r(Container.DataItem,"nmenu_name")%>'>
</asp:Label>
<asp:Label id=lblID runat="server" Font-Size="10pt" Text='<%# DataBinder.eval_r(Container.DataItem,"nmenu_id")%>' Visible="False">
</asp:Label></TD>
</TR>
<TR>
<TD align="center">
<asp:CheckBoxList id="cbSelect" runat="server" Font-Size="10pt" RepeatColumns="2" Width="100%" BackColor="#FFE0C0"
RepeatDirection="Horizontal" DataTextField="nmenu_tname" DataValueField="nmenu_tid"></asp:CheckBoxList></TD>
</TR>
</TABLE>
</ItemTemplate>
</asp:DataList>

后台绑定CheckBox:

 private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
{
if(Session["UID"]!=null&&Session["UID"].ToString()!="")
{
BindList();
BindCheckBox();
}
else
{
Server.Transfer("error.aspx");
}
}
}
private void BindList()
{
string sql = "select * from NewsOne";
DataList1.DataSource = ort.ExecuteToTable(sql);
DataList1.DataBind();
}
private void BindCheckBox()
{
foreach(DataListItem dli in DataList1.Items)
{
CheckBoxList cbl = (CheckBoxList)dli.FindControl("cbSelect");
Label lbl = (Label)dli.FindControl("lblID");
string sql = "select * from NewsTwo where nmenu_oid="+lbl.Text;
cbl.DataSource = ort.ExecuteToTable(sql);
cbl.DataBind();
}
}

CheckBox取值:

 string list = "";
foreach(DataListItem dli in DataList1.Items)
{
CheckBoxList cbSel = (CheckBoxList)dli.FindControl("cbSelect");
for(int i=;i<cbSel.Items.Count;i++)
{
if(cbSel.Items[i].Selected == true)
{
list += cbSel.Items[i].Value + ",";
}
}
}
list = list.Trim(",".ToCharArray());

有的时候会出现取不到值的情况,我的看法是缺少if(!IsPostBack)。