動態訪問DetailsView內的控制項

來源:互聯網
上載者:User
做項目時用到了DetailsView控制項,在EditItemTemplate中需要自己初始一個DropDownList的資料。我曾嘗試在DetailsView控制項的ModeChanging或ModeChanged事件中使用FindControl方法來擷取目標控制項的訪問,但是都失敗了。

我是利用DropDownList_DataBinding事件來解決,給在DetailsView控制項TemplateField中的DropDownList加上onDataBinding事件命令。然後在cs中處理這個事件就OK了。

DetailsView的aspx中代碼如下(省略資料來源代碼):

1 <asp:DetailsView ID="DetailsView1" DataKeyNames="ClassID"
 2     runat="server" DataSourceID="SqlDataSource1" AutoGenerateRows="False" >
 3     <Fields>
 4     <asp:BoundField HeaderText="分類名稱" DataField="ClassTitle" />
 5     <asp:TemplateField HeaderText="所屬分類">
 6     <ItemTemplate>
 7     <%#Eval("ParentTitle") %>
 8     </ItemTemplate>
 9     <EditItemTemplate>
10         <asp:DropDownList ID="ddlParent" runat="server" onDataBinding="ddlParent_DataBinding">
11         </asp:DropDownList>
12     </EditItemTemplate>
13     </asp:TemplateField>
14     <asp:CommandField ShowEditButton="True" />
15     </Fields>
16 </asp:DetailsView>

cs檔案中:
1     protected void ddlParent_DataBinding(object sender, EventArgs e)
2     {
3         //添加資料繫結代碼
4         //BindDropDownList((DropDownList)sender);
5     }

注意:

失敗是因為調用FindControl方法太早了,你得在DetailsView的ItemCreated事件或者是PreRender事件裡做才行。

protected void DetailsView1_PreRender(object sender, EventArgs e)
{
if (IsPostBack)
{
DetailsView detailsView = (DetailsView)sender;
if (detailsView.CurrentMode == DetailsViewMode.Edit)
{
DropDownList dropDownList = (DropDownList)detailsView.FindControl("DropDownList1");
dropDownList.Items.Add(new ListItem("text", "value"));
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.