2017-09-09 93 views
2

我想從我的GridView使用FindControl,但FindControl總是返回爲NULL返回所選行的文本值。在RowDataBound-事件返回查找控制NULL /空

.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

正如上面@AlexKurryashev評論你必須檢查/從EditTemplate模式的GridView的找到控制:

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

OR

您可以使用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"); 
     } 
    }