我想在GridView的标题中有一个DropDownList。在我的代码隐藏中,我似乎无法访问它。这是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而不是返回控件。如何访问控件?
答案 0 :(得分:5)
使用Repeater,您可以使用OnItemDataBoundEvent中的FindControl访问headerTemplate项目,如下所示:
RepeaterItem item = (RepeaterItem)e.Item;
if (item.ItemType == ListItemType.Header) {
item.FindControl("control"); //goes here
}
这对GridViews也有效吗?
答案 1 :(得分:2)
protected void ObjectDataSource1__RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
DropDownList typeFilter = (DropDownList)GridView1.FindControl("TypeFilter");
}
}
答案 2 :(得分:2)
private void GetDropDownListControl()
{
DropDownList TypeFilter = ((DropDownList)this.yorGridView.HeaderRow.FindControl("TypeFilter"));
}
答案 3 :(得分: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();
}
}
}
答案 4 :(得分:0)
尝试使用此方法在HeaderTemplate中查找没有row-data-bind的控件,如果需要的话:
private void Lab_1_GV1_Populate_SearchText()
{
GridView GV1 = (GridView)FindControl("Lab_1_GV1");
TextBox TXB1 = (TextBox)GV1.HeaderRow.FindControl("Lab_1_TX2GV1");
}
谢谢
Ruchir