日期:2014-05-18  浏览次数:20416 次

为何repeater中无法判断CheckBox的Checked?
经过debug发现无论勾选几个,chk.Checked始终等于false

CheckBox chk = (CheckBox)Rp.FindControl("chkMsg");这行代码已确定可以找到控件chkMsg

请问高手,为什么chk.Checked的值总是false?

C# code

        foreach (RepeaterItem Rp in this.msgRepeater.Items)
        {
            CheckBox chk = (CheckBox)Rp.FindControl("chkMsg");
            {
                if (chk.Checked)
                {
                    Label lbl = (Label)Rp.FindControl("lblMsg");
                    id = lbl.Text;
                    cmd.CommandText = "delete from msg where msgID = " + Convert.ToInt32(id);
                    cmd.ExecuteNonQuery();                
                }

            }
        }



------解决方案--------------------
PagelOAD里面绑定的代码没有!ispostback
或者不在<form runat=server>里面
------解决方案--------------------
找到你程序中的所有
this.msgRepeater.DataBind(); 这一行
或者
msgRepeater.DataBind(); 这一行
然后下断点


再在以下代码的红色行下断点
foreach (RepeaterItem Rp in this.msgRepeater.Items)
{
CheckBox chk = (CheckBox)Rp.FindControl("chkMsg");
{
if (chk.Checked)
{
Label lbl = (Label)Rp.FindControl("lblMsg");
id = lbl.Text;
cmd.CommandText = "delete from msg where msgID = " + Convert.ToInt32(id);
cmd.ExecuteNonQuery();
}

}
}


然后你起调试,当你想触发红色行的时候,看一下是否断点执行到了绿色行。
如果执行到了绿色行就会出现你开头说的情况,因为重新做了绑定并且默认所有的复选框都没有被选中
------解决方案--------------------
先将<asp:CheckBox ID= "chkMsg " Visible = "false " runat= "server "/> 
改为<asp:CheckBox ID= "chkMsg " Checked="True" runat= "server "/> 
然后查找所有的msgRepeater.DataBind(),把它改为如下语句
if(!IsPostback) 

msgRepeater.DataBind()

最后在page_load事件的第一行添加如下代码
foreach (RepeaterItem Rp in this.msgRepeater.Items) 

CheckBox chk = (CheckBox)Rp.FindControl( "chkMsg ");

在红色行设置断点查看chk的值
------解决方案--------------------
//对有没有选中进行判断直接按删除按钮则报错
bool strDrive = false;
try
{
SQLT.SetSQLBeginTrans();
for (int i = 0; i < dlHuanzhe.Items.Count; i++)
{
CheckBox CB = (CheckBox)dlHuanzhe.Items[i].FindControl("chk");

if (CB.Checked)
{
strDrive = true;
//隐藏传递ID用一个datatlist就是Parent一个
string delID = ((HiddenField)dlHuanzhe.Items[i].FindControl("id")).Value;

SQLT.Operate("delete from F_Patient where id=" + delID);
}
}
SQLT.SetSQLCommitTrans();
SQLT.ConClose();
}
catch
{
SQLT.SetSQLRollBack();
MessageBox("00006", null);
SQLT.ConClose();
}
if (!strDrive)//判断选中没有
{
MessageBox("00005", null);
}
else//删除后重新绑定
{
//删除后进行重新取总人数
//this.lblRenNum.Text = CalculateRecord().ToString();
this.BindShowF_Patient();