2009-03-05 98 views
8

我想在GridView的標題中使用DropDownList。在我的代碼隱藏中,我似乎無法訪問它。這裏是HeaderTemplate中:如何訪問我的GridView的HeaderTemplate中的控件

<asp:TemplateField SortExpression="EXCEPTION_TYPE"> 
    <HeaderTemplate> 
     <asp:Label ID="TypeId" runat="server" Text="Type" ></asp:Label> 
     <asp:DropDownList ID="TypeFilter" runat="server" AutoPostBack="true"> 
     </asp:DropDownList> 
    </HeaderTemplate> 
    ... 
</asp:TemplateField> 

這裏是在我試圖訪問控制後面的代碼段「TypeFilter」。

protected void ObjectDataSource1_Selected(object sender, 
              ObjectDataSourceStatusEventArgs e) 
{ 
    DataTable dt = (DataTable)e.ReturnValue; 
    int NumberOfRows = dt.Rows.Count; 
    TotalCount.Text = NumberOfRows.ToString(); 
    DataView dv = new DataView(dt); 
    DataTable types = dv.ToTable(true, new string[] { "EXCEPTION_TYPE" }); 
    DropDownList typeFilter = (DropDownList)GridView1.FindControl("TypeFilter"); 
    typeFilter.DataSource = types; 
    typeFilter.DataBind(); 

} 

您會注意到我正在嘗試使用FindControl來獲取對DropDownList控件的引用。該調用返回null而不是返回控件。我如何獲得控制權?

回答

5

帶中繼器,您使用的FindControl訪問HeaderTemplate中的項目在OnItemDataBoundEvent這樣的:

RepeaterItem item = (RepeaterItem)e.Item; 
if (item.ItemType == ListItemType.Header) { 
    item.FindControl("control"); //goes here 
} 

這是否工作GridView的呢?

2
protected void ObjectDataSource1__RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.RowType == DataControlRowType.Header) 
     { 
      DropDownList typeFilter = (DropDownList)GridView1.FindControl("TypeFilter"); 
     } 
    } 
0
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
if (e.Row.RowType == DataControlRowType.Header) 
{ 
DropDownList ddlLocation = (DropDownList)e.Row.FindControl("ddlLocation"); 
ddlLocation.DataSource = dtLocation; 
ddlLocation.DataBind(); 
} 
} 
} 
2
private void GetDropDownListControl() 
    { 
     DropDownList TypeFilter = ((DropDownList)this.yorGridView.HeaderRow.FindControl("TypeFilter")); 
    } 
0

試試這個找到在沒有行的數據綁定的HeaderTemplate中的控件,如果這是需要什麼:

private void Lab_1_GV1_Populate_SearchText() 
    { 
     GridView GV1 = (GridView)FindControl("Lab_1_GV1"); 
     TextBox TXB1 = (TextBox)GV1.HeaderRow.FindControl("Lab_1_TX2GV1"); 
    } 

感謝

Ruchir

相關問題