2010-07-28 35 views
0

在asp.net中有時一個webcontrol需要引用另一個webcontrol,比如gridview需要它綁定到的數據源對象的id。Webcontrol作爲另一個webcontrol的屬性

我有我的webcontrol屬性是一個字符串(我想參考的webcontrol的id)。如何根據此ID訪問實際的Web控件?

回答

1
+0

FindControl只在任何給定的容器中看起來。但是,如果這是唯一可用於這種情況的工具,那麼解決方案是構建一個遍歷頁面結構並返回與提供的id相匹配的控件的遞歸方法。 – SynBiotik 2010-07-28 14:39:29

+0

嗯......但是不是Page.FindControl()搜索整個頁面? – cRichter 2010-07-29 09:07:52

+0

它不應該: 「FindControl方法可用於訪問在設計時ID不可用的控件。該方法僅搜索頁面的即時或頂級容器;它不會遞歸搜索命名頁面中包含的容器要訪問下級命名容器中的控件,請調用該容器的FindControl方法。「 - http://msdn.microsoft.com/en-us/library/31hxzsdw.aspx – SynBiotik 2010-07-29 13:15:52

0

下面是結合到一個ObjectDataSource一個GridView的樣品,與所述的ObjectDataSource結合爲一個參數一個DropDownList。這應該讓你開始。

<asp:GridView ID="GridView1" runat="server" 
    AutoGenerateColumns="False" 
    DataSourceID="CustomerObjectDataSource" 
    DataKeyNames="CustomerID" 
    AllowPaging="True" 
    AllowSorting="True" AutoGenerateDeleteButton="True" 
    AutoGenerateEditButton="True" AutoGenerateSelectButton="True" 
    onrowdeleted="GridView1_RowDeleted" onrowupdated="GridView1_RowUpdated"> 
    <Columns> 
     ... 
    </Columns> 
</asp:GridView> 

<asp:ObjectDataSource ID="CustomerObjectDataSource" runat="server" 
    EnablePaging="True" 
    MaximumRowsParameterName="totalRows" 
    StartRowIndexParameterName="firstRow" 
    TypeName="Northwind.Business.CustomerSource" 
    DataObjectTypeName="Northwind.Business.CustomerDTO" 
    SelectMethod="Load" 
    UpdateMethod="Save" 
    InsertMethod="Insert" 
    DeleteMethod="Delete" 
    SelectCountMethod="CustomerCount" 
    SortParameterName="sortExpression"> 
    <SelectParameters> 
     <asp:ControlParameter ControlID="ddlRegion" Name="region" 
      PropertyName="SelectedValue" /> 
    </SelectParameters> 
</asp:ObjectDataSource>  
+0

仍然存在的問題是:gridview是否通過使用FindControl方法遞歸遍歷頁面來定位ObjectDataSource? – SynBiotik 2010-07-28 14:40:17

+0

@SynBiotik,no。 GridView標記的DataSourceID字段通過數據源的ID標識ObjectDataSource。綁定是顯式的(在上面的示例代碼中,「CustomerObjectDataSource」)。 – 2010-07-28 19:52:57

+0

IHere是DataSourceId代碼: 公共虛擬字符串DataSourceID { 得到 {obj2 = this.ViewState [「DataSourceID」]; if(obj2!= null) { return(string)obj2; } return string.Empty; } 設置 { 如果 { this._requiresBindToNull =真(string.IsNullOrEmpty(值)&& string.IsNullOrEmpty(this.DataSourceID)!); } this.ViewState [「DataSourceID」] = value; this.OnDataPropertyChanged(); } } gridview如何將字符串綁定到實際的對象? – SynBiotik 2010-07-29 10:55:16

相關問題