Skip to main content
 首页 » 编程设计

c#之遍历 gridview 并不总是有效

2024年02月13日11zhoujg

不确定是什么原因造成的,我尝试了一些建议,但似乎都无济于事。我已经调试了我的应用程序数十次,并且在调试所有步骤时都没有出现问题。但是当我发布我的应用程序并允许人们使用它时,问题就出现了,并不是每个人都随机决定不选中复选框并跳过前端的整个过程我有一个验证至少需要在 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 

请您参考如下方法:

我相信 grdEventDetail GridView 在每一行中没有 CheckBoxes。例如,HeaderRow 和 FooterRow 可能没有这些复选框。

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

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 
            } 
        } 
    } 
}