簡體   English   中英

在GridView的EditTemplates中使用DropDownList

[英]Using DropDownList in EditTemplates of a GridView

我正在使用Asp.Net中的GridView。 最初頁面加載時,我的gridview看起來像: alt text http://www.freeimagehosting.net/uploads/e45e5b66d4.jpg

當用戶單擊,編輯行時,我使用編輯模板在DropDownList中顯示“域”。 但問題是,當DropDownlist加載數據時,它會丟失“域”的當前值。
如果我想編輯第4行,其當前設置為“計算機”的域將變為“MBA” ,這當然是DataSource返回的第一個元素。 alt text http://www.freeimagehosting.net/uploads/7d3f6ba9a5.jpg


我想在DropDownList中顯示當前值('computers')作為選定值。 但是我無法獲得正在編輯的Domain的值。

您可以綁定下拉列表的SelectedValue屬性,如下所示:

SelectedValue='<%# Eval("Domain") %>'

但是,如果綁定不存在的值,則會引發異常。 因此,您可能需要根據您的方案處理代碼。

編輯:如果該值不存在,則不幸的剩余解決方案將進入gridview的RowDataBound並獲取對下拉的引用,並執行:

MyBoundObject obj = (MyBoundObject)e.Row.DataItem;
DropDownList ddl = (DropDownList)e.Row.Cells[<index>].FindControl("ddl1");
ListItem item = ddl.Items.FindByValue(obj.Domain);
if (item != null) item.Selected = true;

此處,僅當列表項存在時才會選中它。 如果沒有選擇項目,請嘗試ddl.SelectedValue = item.Value。

HTH。

解決異常使用AppendDataBoundItems =“true”。

<asp:DropDownList ID="ddlCategory" runat="server" SelectedValue='<%# Eval("Domain") %>' 
        DataSourceID="datasource"
            DataTextField="text" DataValueField="value" AppendDataBoundItems="true">
            <asp:ListItem Text="Select..." Value=""></asp:ListItem>
        </asp:DropDownList>

這可能對您有所幫助:

監聽事件RowEditing,使用.FindControl()方法獲取特定行的Dropdownlist,並在DDL上執行顯式.DataBind()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM