Asp.net
Gridview 行編輯 - 動態綁定到 DropDownList
我試圖讓一個 ASP.NET 3.5 GridView 在顯示時將選定的值顯示為字元串,並顯示一個 DropDownList 以允許我在編輯時從給定的選項列表中選擇一個值。看起來很簡單?
我的 gridview 看起來像這樣(簡化):
<asp:GridView ID="grvSecondaryLocations" runat="server" DataKeyNames="ID" OnInit="grvSecondaryLocations_Init" OnRowCommand="grvSecondaryLocations_RowCommand" OnRowCancelingEdit="grvSecondaryLocations_RowCancelingEdit" OnRowDeleting="grvSecondaryLocations_RowDeleting" OnRowEditing="grvSecondaryLocations_RowEditing" OnRowUpdating="grvSecondaryLocations_RowUpdating" > <Columns> <asp:TemplateField> <ItemTemplate> <asp:Label ID="lblPbxTypeCaption" runat="server" Text='<%# Eval("PBXTypeCaptionValue") %>' /> </ItemTemplate> <EditItemTemplate> <asp:DropDownList ID="ddlPBXTypeNS" runat="server" Width="200px" DataTextField="CaptionValue" DataValueField="OID" /> </EditItemTemplate> </asp:TemplateField> </asp:GridView>網格在不處於編輯模式時顯示正常 - 選定的 PBX 類型在 asp:Label 控制項中顯示其值。那裡並不奇怪。
我將 DropDownList 的值列表載入到表單事件中呼叫
_pbxTypes的本地成員中。OnLoad我驗證了這一點 - 它有效,值在那裡。現在我的挑戰是:當網格進入特定行的編輯模式時,我需要綁定儲存在
_pbxTypes.很簡單,我想 - 只需抓住事件中的下拉列表對象
RowEditing並附加列表:protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e) { grvSecondaryLocations.EditIndex = e.NewEditIndex; GridViewRow editingRow = grvSecondaryLocations.Rows[e.NewEditIndex]; DropDownList ddlPbx = (editingRow.FindControl("ddlPBXTypeNS") as DropDownList); if (ddlPbx != null) { ddlPbx.DataSource = _pbxTypes; ddlPbx.DataBind(); } .... (more stuff) }麻煩的是 - 我從來沒有從
FindControl電話中得到任何回報 - 似乎ddlPBXTypeNS不存在(或找不到)。我錯過了什麼??一定是真的很愚蠢……但到目前為止,我所有的Google搜尋、閱讀 GridView 控制項和詢問好友都沒有幫助。
誰能發現缺失的連結?;-)
很容易……你做錯了,因為在那個事件中,控制項不存在:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit) { // Here you will get the Control you need like: DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS"); } }也就是說,它僅對
DataRow(實際包含數據的行)有效,並且如果它處於編輯模式……因為您一次只能編輯一行。e.Row.FindControl("ddlPBXTypeNS")只會找到您想要的控制項。