2017-09-09 7 views
2

FindControl을 사용하여 GridView에서 선택한 행의 텍스트 값을 가져 오려고 시도하지만 FindControl은 항상 NULL로 반환됩니다.NULL/빈으로 RowDataBound-Event 반환 컨트롤을 찾습니다.

.ASPX 코드 :

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CID" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound"> 
    <Columns> 
     <asp:CommandField ShowSelectButton="True" /> 
     <asp:BoundField DataField="CID" HeaderText="CID" InsertVisible="False" ReadOnly="True" SortExpression="CID" /> 
     <asp:BoundField DataField="CountryID" HeaderText="CountryID" SortExpression="CountryID" /> 
     <asp:TemplateField HeaderText="CountryName" SortExpression="CountryName"> 
      <EditItemTemplate> 
       <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CountryName") %>'></asp:TextBox> 
      </EditItemTemplate> 
      <ItemTemplate> 
       <asp:Label ID="Label1" runat="server" Text='<%# Bind("CountryName") %>'></asp:Label> 
      </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

C# 코드 :

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     TextBox txt = e.Row.FindControl("TextBox1") as TextBox; 
     string name = txt.Text; // returns as NULL 
    } 
} 

사람이 내가 잘못 여기서 뭐하는 거지 또는이 일을 다른 방법이 무엇인지 지적 할 수 있습니까? 선택 버튼을 클릭하면 위의 GridView에서 CountryName 값을 얻고 싶습니다.

+2

'ID = "TextBox1"이 (가)있는 컨트롤은'EditItemTemplate'에만 있습니다. 'e.Row.RowState == DataControlRowState.Edit'을 시도하십시오. 또는'TextBox'와'Label'에 같은 ID를 부여하십시오. –

답변

1

으로 당신의 GridView의 EditTemplate 모드에서 컨트롤을 찾을 수/확인해야 코멘트 위 @AlexKurryashev :

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    // check if its not a header or footer row 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // check if its in a EditTemplate 
     if (e.Row.RowState == DataControlRowState.Edit) 
     { 
      TextBox txt = e.Row.FindControl("TextBox1") as TextBox; 
      string name = txt.Text; 
     } 
    } 
} 

또는

다음과 같이 선택 버튼 클릭에서 값을 가져 OnRowCommand 이벤트를 사용할 수 있습니다

:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    if (e.CommandName == "Select") 
    { 
     // get row where clicked 
     GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer); 

     Label txt = row.FindControl("Label1") as Label; 
     string name = txt.Text; 
    } 
} 
1

둘 다 감사합니다! "ItemTemplate"에서 데이터를 가져올 수있었습니다. 그러나 이번에는 다른 이벤트를 사용했습니다.

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     { 
      Label txt = GridView1.SelectedRow.FindControl("Label1") as Label; 
      string name = txt.Text; 
      Label2.Text = name; 

      Session["Name"] = name; 
      Response.Redirect("check.aspx"); 
     } 
    }