2014-09-11 1 views
0

다른 gridview 내부에 중첩 된 gridview가 있습니다. 부모 그리드 뷰에는 작업 목록이 있으며 각 작업에는 단계 목록 (하위 그리드 뷰)이 있습니다. 각 단계에는 확인란이 있으므로 사용자가 단계를 완료하면 확인란을 선택하면 체크 된 단계가 완료 될 때까지 데이터베이스를 업데이트하는 저장 프로 시저가있는 CheckChanged 이벤트가 발생합니다.체크 상자가 선택된 중첩 된 gridview에서 필드 값을 얻으려면 어떻게해야합니까?

체크 체크 박스가있는 행의 단계 ID를 찾고 입력 ID로 단계 ID를 사용하여 저장 프로 시저를 시작하는 CheckChanged 이벤트가 있습니다. 이 작동합니다. 그러나 단계를 추가 할 수 있으며 어떤 이유로 이전 단계의 확인란을 클릭하면 단계 ID를 찾는 코드가 뒤로 이동하지 않고 단계 ID를 인식합니다. 다시 말해, 특정 작업의 단계 ID가 20이고 그것이 검사되고 이벤트가 시작되면 이전 작업 (gridview에서 더 높은 작업)에 단계를 추가하고 해당 단계에 CheckChanged 이벤트가 다른 작업에 추가 된 단계를 인식하지 못하는 것처럼 21의 ID를 클릭하면 단계 ID가 20으로 계속 등록됩니다. 여기 내 코드입니다 :

영문 :

<asp:GridView ID="GridView1" 
       DataKeyNames="TaskID" 
       runat="server" 
       OnRowDataBound="GridView1_OnRowDataBound" 
       CssClass="DefaultGrid" 
       onRowCommand="GridView1_RowCommand" 
       EmptyDataText = "<br/>There are no Tasks in this Project." 
       AllowPaging="True" 
       AllowSorting="True" 
       CellPadding="4" 
       DataSourceID="SqlDataSource_mp_Display_Tasks_Home" 
       ForeColor="#333333" 
       GridLines="None" 
       AutoGenerateColumns="False"> 
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> 
    <RowStyle CssClass=" table-responsive body-content " /> 
    <Columns> 
     <asp:CommandField ShowSelectButton="False" />   
     <asp:TemplateField> 
      <ItemTemplate> 
       <img alt = "" style="cursor: pointer" src="Images/plus.png" />           
       <asp:Panel ID="pnlOrders" runat="server" Style="display:none">           
        <asp:GridView ID="GridView2" 
            runat="server" 
            onRowCommand="GridView2_RowCommand" 
            Datakeynames="TaskStepID" 
            CssClass="ChildGrid" 
            EmptyDataText="<br/>There are no Steps in this Task." 
            AutoGenerateColumns="false" 
            onselectedindexchanged="GridView2_SelectedIndexChanged"> 
         <Columns>                  
          <asp:BoundField DataField="TaskStepID" HeaderText="TaskStepID" Visible="true" /> 
          <asp:BoundField DataField="TaskID" HeaderText="TaskID" Visible="false" /> 
          <asp:BoundField DataField="TaskStepTypeID" HeaderText="TaskStepTypeID" Visible="false"/> 
          <asp:BoundField DataField="TaskStepPriority" HeaderText="Task Step Priority" Visible="false" /> 
          <asp:BoundField ItemStyle-Width="70%" DataField="TaskStepDesc" HeaderText="Step Description" />         
          <asp:TemplateField HeaderText="Step Completed" ItemStyle-Width="15%" > 
           <ItemStyle HorizontalAlign="Center" /> 
           <ItemTemplate> 
            <asp:Checkbox ID="TaskStepCompleted" 
                OnCheckedChanged="TaskStepCompleted_CheckedChanged" 
                Checked='<%# Eval("TaskStepCompleted") %>' 
                runat="server"                              
                AutoPostBack="true" />               
           </ItemTemplate>                
          </asp:TemplateField> 
          <asp:BoundField DataField="TaskStepComment" HeaderText="TaskStepComment" Visible="false" /> 
          <asp:TemplateField HeaderText="Step Activity" ItemStyle-Width="15%"> 
           <ItemTemplate>  
            <asp:LinkButton Text="Add" ID="Addstep" runat="server" CommandName="addstep" CommandArgument='<%# Eval("TaskStepID") %>'/> 
            <asp:LinkButton Text="Edit" ID="Editstep" runat="server" CommandName="editstep" CommandArgument='<%# Eval("TaskStepID") %>'/>                
            <asp:LinkButton Text="Delete" ID="Deletestep" runat="server" CommandName="deletestep" OnClientClick="return confirm('<%=AlertMe%>');" CommandArgument='<%# Eval("TaskStepID") %>'/>                         
           </ItemTemplate>                
          </asp:TemplateField> 
         </Columns> 
        </asp:GridView> 
       </asp:Panel> 
      </ItemTemplate> 
     </asp:TemplateField> 
     <asp:BoundField DataField="TaskID" HeaderText="Task ID" Visible="false"/> 
     <asp:BoundField DataField="ProjectID" HeaderText="Project ID" Visible="false" />    
     <asp:BoundField DataField="TaskTypeID" HeaderText="Task Type ID" Visible="false" /> 
     <asp:BoundField DataField="TaskCompleted" HeaderText="Taske Completed?" Visible="false" />     
     <asp:BoundField DataField="TaskCreationDate" HeaderText="Task Creation Date" Visible="false" /> 
     <asp:BoundField DataField="TaskSubmitterID" HeaderText="Task Submitter ID" Visible="false" /> 
     <asp:BoundField DataField="DepartmentID" HeaderText="DepartmentID" Visible="false" /> 
     <asp:BoundField DataField="TaskDueDateCommentType" HeaderText="Due Date Comment" Visible="false" /> 
     <asp:BoundField DataField="TaskLastUpdatedDate" HeaderText="Task Last Updated Date" Visible="false" /> 
     <asp:BoundField DataField="TaskLastUpdatedUserID" HeaderText="Task Last Updated UserID" Visible="false" />     
     <asp:BoundField DataField ="TaskSubmitterName" HeaderText="Task Submitter Name" Visible="false" /> 
     <asp:BoundField DataField="TaskLastUpdatedUser" HeaderText="Task Last Updated User" Visible="false" />     
     <asp:BoundField DataField="DepartmentDesc" HeaderText="Dept" visible="false"/> 
     <asp:TemplateField HeaderText="Task Description"> 
      <ItemTemplate> 
       <asp:Label ID="TaskDescription" runat="server" Text='<%# HighlightText(Eval("TaskDescription").ToString()) %>'></asp:Label> 
      </ItemTemplate> 
      <ItemStyle Width="40%" /> 
     </asp:TemplateField> 
     <asp:TemplateField HeaderText="% Comp."> 
      <ItemStyle HorizontalAlign="Center" /> 
      <ItemTemplate> 
       <asp:Label ID="PercentCompleted" runat="server" Text='<%# (String.IsNullOrEmpty(Eval("PercentCompleted").ToString()) ? "0" : Eval("PercentCompleted")) + " %" %>' ></asp:Label> 
      </ItemTemplate> 
     </asp:TemplateField> 
     <asp:BoundField DataField="TaskDueDate" HeaderStyle-HorizontalAlign="Right" HeaderText="Task Due Date" DataFormatString="{0:MM-dd-yyyy}" visible="true"/> 
     <asp:BoundField DataField="TaskTypeName" HeaderText="Task Type" visible="true" /> 
     <asp:BoundField DataField="DepartmentAbbrev" HeaderText="Dept" Visible="true" /> 
     <asp:TemplateField HeaderText="Activity"> 
      <ItemTemplate>  
      <asp:LinkButton Text="Edit" ID="Edittask" runat="server" CommandName="edittask" CommandArgument='<%# Eval("TaskID") %>'/>                
      <asp:LinkButton Text="Delete" ID="Deletetask" runat="server" CommandName="deletetask" OnClientClick="return confirm('Are you sure you wish to Delete this Task?');" CommandArgument='<%# Eval("TaskID") %>'/>                         
      <asp:LinkButton Text="Comments" ID="Detailstask" runat="server" CommandName="detailstask" CommandArgument='<%# Eval("TaskID") %>'/> 
      </ItemTemplate>                
     </asp:TemplateField> 
    </Columns>   
    <EditRowStyle BackColor="#999999" /> 
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> 
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> 
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> 
    <SortedAscendingCellStyle BackColor="#E9E7E2" /> 
    <SortedAscendingHeaderStyle BackColor="#506C8C" /> 
    <SortedDescendingCellStyle BackColor="#FFFDF8" /> 
    <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> 
</asp:GridView> 
<asp:SqlDataSource ID="SqlDataSource_mp_Display_Tasks_Home" runat="server" FilterExpression="TaskDescription LIKE '%{0}%'" ConnectionString="<%$ ConnectionStrings:IntelliBaseConnectionString_mp_Display_Projects_Home %>" SelectCommand="mp_Display_Tasks_Home" SelectCommandType="StoredProcedure" ProviderName="System.Data.SqlClient"> 
    <SelectParameters> 
     <asp:Parameter Name="Incoming_ProjectID" Type="Int32" />       
    </SelectParameters> 
    <FilterParameters> 
     <asp:ControlParameter Name="TaskDescription" ControlID="txtSearchtasks" PropertyName="Text"/> 
    </FilterParameters> 
</asp:SqlDataSource> 

CS :

protected void TaskStepCompleted_CheckedChanged(object sender, EventArgs e) 
{ 
    // this nested foreach grabs the taskstepID number for the row in which the checkbox was just checked. 
    foreach (GridViewRow row in GridView1.Rows) 
    { 
     if (row.RowType == DataControlRowType.DataRow) 
     { 
      GridView GridView2 = (GridView)row.FindControl("GridView2"); 

      if (GridView2 != null) 
      { 
       foreach (GridViewRow Row in GridView2.Rows) 
       { 
        if (Row.RowType == DataControlRowType.DataRow) 
        { 
         System.Web.UI.WebControls.CheckBox chk = (System.Web.UI.WebControls.CheckBox)Row.FindControl("TaskStepCompleted"); 
         if (chk.Checked || !chk.Checked) 
         { 
          Session["TaskStepID"] = GridView2.DataKeys[Row.RowIndex]["TaskStepID"].ToString(); 
         } 
        } 
       } 
      } 
     } 
    } 

    // autopost back the check box to run the stored procedure 
    var TaskStepID = Session["TaskStepID"].ToString(); 
    var ProjectID = Session["ProjectID"].ToString(); 

    using (var conn = new SqlConnection("Data Source=orlandosql1;Initial Catalog=IntelliBase;Persist Security Info=True;User ID=trainingsurveys_webuser;[email protected];")) 
    using (SqlCommand cmd = new SqlCommand("dbo.mp_Task_Step_Completed_Toggle", conn)) 
    { 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Parameters.Add("@TaskStepID", SqlDbType.Int).Value = TaskStepID; 
     cmd.Parameters.Add("@AdminUserID", SqlDbType.Int).Value = "10"; 
     cmd.Parameters.Add("@LogActionItemID", SqlDbType.Int).Value = "15"; 
     cmd.Parameters.AddWithValue("@DTStamp", SqlDbType.DateTime.ToString("d")).Value = DateTime.Now.ToString("d"); 

     conn.Open(); 
     cmd.ExecuteNonQuery(); 
     conn.Close(); 

     Response.Redirect("Tasks.aspx?id=" + ProjectID.ToString()); 
    }   
} 

나는이 문제를 설명하기 위해 최선을 시도했다. 요약하면 중첩 된 gridview에는 확인란이있는 행이 있습니다. 확인란을 클릭하면 db 테이블이 자동으로 업데이트되지만 체크 박스 행과 상관없이 CheckedChanged 코드는 가장 최근 ID의 ID 만 등록합니다. 모든 통찰력이 인정됩니다. 카를로스

답변

0

만약 내가 제대로 이해하고

, 나는 당신의 문제는 당신이 당신의 GridViewRow의 TaskStepID를 잡아 생각하는 방법을 함께 제공 믿습니다. 당신은 많은 불필요한 작업을하고 있습니다. 두 GridViews의 모든 행을 반복하는 대신 방금 클릭 한 CheckBox의 GridViewRow를 가져옵니다.

CheckBox cb = (CheckBox)sender; 
GridViewRow row = (GridViewRow)cb.NamingContainer; 
GridView gv = (GridView)row.NamingContainer; 
string taskStepID = gv.DataKeys[row.RowIndex].Value.ToString(); 

주의는 어떻게 것처럼 각 행을 반복함으로써, 당신은 항상 마지막 행의 TaskStepID을 받고 있었다. 따라서 행 앞에 행을 추가하면 예상 한 행 대신 마지막 행이 사용됩니다.

+0

정확히 내 문제입니다! 행 인덱스를 찾는 훨씬 좋은 솔루션 인 것 같습니다. 그러나 Gridview2는 컨텍스트에 맞지 않습니다. 두 gridviews의 모든 행을 반복 할 필요없이 어떻게 컨텍스트에 넣을 수 있습니까? – user3589434

+0

죄송합니다. 죄송합니다. 내 편집을 확인하십시오. 당신이 원하는 것은 컨트롤의 NamingContainer가 행을 가져 오는 것입니다. 그런 다음 행의 NamingContainer를 찾아 GridView를 가져옵니다. NamingContainer는 INamingContainer를 구현하는 컨트롤을 찾을 때까지 컨트롤 트리를 확장합니다. –

+0

이것은 트릭을 만들었습니다! 정말 고맙습니다! – user3589434

관련 문제