asp.net
  • gridview
  • templatefield
  • rowcommand
  • 2009-11-03 6 views 2 likes 
    2
    <asp:TemplateField>  
        <ItemTemplate> 
         <table width="540" cellpadding="5"> 
         <tr> 
          <td align="left" style="width:60%;"> 
           <img src='PurchaseHandler.ashx?ProductID=<%# Eval("ProductID")%>' 
            alt="<%# Eval("ProductName") %>" /> 
          </td> 
          <td align="left"> 
           <h3 style="text-align:left;"> 
            <asp:Label ID="nameLabel" runat="server" 
             Text='<%# Eval("ProductName") %>' /> 
           </h3> 
           <asp:Label ID="priceLabel" runat="server" Text='<%# Eval("Price") %>' /> 
           <br /> 
           <asp:LinkButton ID="cartLink" runat="server" Text="<b>Add to Cart</b>" 
            CommandName="Add" CommandArgument='<%# Eval("ProductID") %>' /> 
          </td> 
         </tr> 
         </table> 
        </ItemTemplate> 
    </asp:TemplateField> 
    

    GridView에 표시되지 않는 필드를 포함하는 장바구니 비즈니스 개체를 사용하고 있습니다. RowCommand 이벤트 핸들러에서 다음에 수행하려는 작업은 선택한 행에서 나머지 데이터 필드를 검색하는 것입니다. 이것은 나에게 선택된 행에서 올바른 제품 ID를 제공합니다GridView 템플릿 - 선택한 행의 데이터를 가져 오는 방법

    if (e.CommandName == "Add") 
    { 
        int productID = 0; 
        int.TryParse(e.CommandArgument as string, out productID); 
    
        // Big blank! 
    } 
    

    어떻게 내 장바구니를 채우는 선택된 행에서 데이터 필드의 나머지 부분을 잡아 수 있습니까? 설명을 위해, 아마도 ProductID를 사용하여 Session 상태에서 가져온 DataSet을 파고 그 방식으로 데이터를 얻을 수 있습니다. 그러나,이 상황에서 사용할 수있는 비슷한 구문이 있는지 확인하려면 무엇을 시도하고 있습니까?

    DataRow[] rows = ds.Tables[0].Select("ProductID=" + 
            gridProducts.SelectedDataKey.Values["ProductID"].ToString()); 
    DataRow row = rows[0]; 
    

    답변

    5

    이 작업을 수행하는 한 가지 방법은 행 인덱스를 저장하기 위해 명령 인수를 사용하는 것입니다 (아마도 on 행 작성 이벤트에 설정).

    그런 다음 (MSDN에서 냈다 코드)하여 행에 액세스하려면 다음과 같이 코드를 사용할 수 있습니다 : 당신이 제품 ID로 명령 인수를 유지해야하는 경우

    // Convert the row index stored in the CommandArgument 
        // property to an Integer. 
        int index = Convert.ToInt32(e.CommandArgument); 
    
        // Retrieve the row that contains the button clicked 
        // by the user from the Rows collection. Use the 
        // CommandSource property to access the GridView control. 
        GridView customersGridView = (GridView)e.CommandSource; 
        GridViewRow row = customersGridView.Rows[index]; 
    

    다음 액세스 아래의 코드를 사용할 수 있습니다 행 :

    GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer); 
    

    당신은 당신이 필요로하는 컨트롤을 선택합니다 GridViewRow의의 FindControl() 메서드를 사용할 수 있습니다.

    Label priceLabel = row.FindControl("priceLabel") as Label; 
    

    편집

    내가 올바른있어 경우에 따라서, 당신은 당신의 행의있는 DataItem에 액세스 할 OP 의견 후에? 나는 다른 포럼에 파고의 조금했고, 분명히이 속성이 DataBind 동안에 만 null가 아닌 - -이이 RowCommand 이벤트 핸들러 내에서 가능하다고 생각하지 않습니다

    MSDN 말을 this 있습니다

    DataItem 속성은 GridView 컨트롤의 RowDataBound 이벤트 중 및 이후에만 사용할 수 있습니다. 당신의 방법 또는 이와 유사한 일이 다시 RowCommand의 원본 개체에 연결하는 유일한 방법처럼

    +0

    안녕하세요 데이비드, 귀하의 의견 감사 (희망 누군가가 잘못 나를 증명) 찾습니다. 나는 데이터 세트에 다른 비 표시 필드가 있다는 것을 설명하기 위해 질문을 편집했다. 나는 이미 얻은 productID를 사용하여 그들에게 다가 갈 수 있습니다. 그러나 뭔가 좀 더 우아한 접근 방식이 나에게 말해 ... TemplateFields는 항상 이런 유형의 시나리오에서 나를 혼란스럽게합니다. Anthony :-) – IrishChieftain

    +0

    감사합니다. David, 답변입니다. DataSet에서 직접 데이터를 가져올 수있었습니다. Anthony :-) – IrishChieftain

    +0

    다른 사람들을 위해서, 앞에서 얻은 productID에 대한 일치 항목을 얻기 위해 DataSet의 테이블 행을 반복하여 선택한 행의 색인을 가져 왔습니다. 그런 다음 나머지 데이터에 액세스 할 수있었습니다. – IrishChieftain

    관련 문제