2013-02-22 43 views
2

我使用一個GridView控件,這裏是我的模板列之一:找不到使用的FindControl上RowCreated的GridView的

<asp:TemplateField HeaderText="Quantity" SortExpression="Quantity"> 
    <HeaderTemplate> 
     <asp:Label ToolTip="Quantity" runat="server" Text="Qty"></asp:Label> 
    </HeaderTemplate> 
    <EditItemTemplate> 
     <asp:TextBox ID="txt_Quantity" runat="server" Text='<%# Bind("Quantity") %>' Width="30px" 
      Enabled='True'></asp:TextBox> 
    </EditItemTemplate> 
</asp:TemplateField> 

我特林達到txt_Quantity這樣

protected void begv_OrderDetail_RowCreated(object sender, GridViewRowEventArgs e) 
    { 
     TextBox txt_Quantity = (TextBox)e.Row.FindControl("txt_Quantity"); 
     txt_Quantity.Attributes.Add("onFocus", "test(this)"); 
    } 

這是錯誤消息:

System.NullReferenceException:對象引用未設置爲實例 的一個對象。

回答

2

RowCreated對每RowType(順便說一句,同樣與RowDataBound)執行,所以用於報頭,數據行,頁腳或尋呼機。

第一行是標題行,但TextBox與行RowType = DataRow。因爲它是在EditItemTemplate你還必須檢查EditIndex

protected void begv_OrderDetail_RowCreated(object sender, GridViewRowEventArgs e) 
{ 
    if (row.RowType == DataControlRowType.DataRow 
     && e.Row.RowIndex == begv_OrderDetail.EditIndex) 
    { 
     TextBox txt_Quantity = (TextBox)e.Row.FindControl("txt_Quantity"); 
     txt_Quantity.Attributes.Add("onFocus", "test(this)"); 
    } 
} 

請注意,如果枚舉GridViewRows屬性,您只用RowType = DataRow得到了行,因此省略頁眉,頁腳和尋呼機。所以這裏不需要額外的檢查:

foreach(GridViewRow row in begv_OrderDetail.Rows) 
{ 
    // only DataRows 
} 
相關問題