循环遍历gridview并不总是有效

时间:2014-02-18 00:23:06

标签: c# asp.net gridview

不确定导致这种情况的原因我尝试了一些似乎没有帮助的建议。我已经调试了几十次我的应用程序,并且在调试所有步骤时,问题永远不会发生。但是,当我发布我的应用程序并允许人们使用它时,问题出现并且不是每个人都只是随机决定不检查复选框并在前端跳过整个过程我有一个验证,至少需要在button_click将触发之前检查一个复选框,因此我知道他们必须检查一个。

的GridView

 <div id="divEventDetail">
    <asp:GridView ID="grdEventDetail" runat="server" AutoGenerateColumns="False" DataKeyNames="EDID" Width="381px" OnRowDataBound="grdEventDetail_RowDataBound" GridLines="Horizontal">
    <Columns>
  <asp:TemplateField HeaderText="EventID" Visible="False">
           <ItemTemplate>
     <asp:Label ID="lblEventID" runat="server" Text='<%#     Eval("EDID") %>'></asp:Label>
           </ItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Register" ItemStyle-CssClass="template-center">
           <ItemTemplate >                         
               <asp:CheckBox ID="chkRegister" runat="server"/>
           </ItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Wait List" ItemStyle-CssClass="template-center">
           <ItemTemplate> 
               <asp:CheckBox ID="chkWaitList" runat="server" />   
           </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    </asp:GridView>
    </div>

代码隐藏

 protected void registerEvent()
        {
            foreach (GridViewRow row in grdEventDetail.Rows)
            {

                CheckBox chkR = row.FindControl("chkRegister") as CheckBox;
                CheckBox chkW = row.FindControl("chkWaitList") as CheckBox;

                if (chkR != null && chkW != null)// It is a datarow
                {

                    GridViewRow Rowr = ((GridViewRow)chkR.Parent.Parent);
                    GridViewRow Roww = ((GridViewRow)chkW.Parent.Parent);

                    if ((chkR.Checked) || (chkW.Checked))
                    // if ((((CheckBox)row.FindControl("chkRegister")).Checked == true) || (((CheckBox)row.FindControl("chkWaitList")).Checked == true))
                    {
                        Label eventID = row.FindControl("lblEventID") as Label;
***Then i do my database stuff here

1 个答案:

答案 0 :(得分:4)

我认为grdEventDetail GridView在每一行中都没有CheckBoxes。例如,HeaderRowFooterRow可能没有那些CheckBox。

我会重写代码以消除任何错误:

protected void registerEvent()
{
    foreach (GridViewRow row in grdEventDetail.Rows)
    {
        CheckBox chkR = row.FindControl("chkRegister") as CheckBox;
        CheckBox chkW = row.FindControl("chkWaitList") as CheckBox;

        if(chkR != null && chkW != null)// It is a datarow
        {
            GridViewRow Rowr = ((GridViewRow)chkR.Parent.Parent);
            GridViewRow Roww = ((GridViewRow)chkW.Parent.Parent);

            if ((chkR.Checked) || (chkW.Checked))  
            {
                //Your code goes here
            }
        }
    }
}