2011-04-03 41 views
3

我有一個gridview,它有一個作者列。我想將作者名稱顯示爲超鏈接,因此當用戶點擊它時,他會被重定向到作者頁面。但是當用戶希望編輯當前產品的作者時,他應該看到一個下拉列表。我想實現它使用模板領域:gridview:顯示鏈接,但編輯下拉列表

<asp:TemplateField HeaderText="автор"> 
     <ItemTemplate> 
      <asp:HyperLink ID="HyperLink1" runat="server" NavigateURL='<%# "~/CMS/AuthorPage.aspx?a="+ Eval("AuthorID")%>' Text='<%#Eval("AuthorID")%>' />          
     </ItemTemplate> 
     <EditItemTemplate> 
       <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource3" 
     DataTextField="Name" DataValueField="ID"/> 
<asp:SqlDataSource ID="SqlDataSource3" runat="server" 
     ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString1 %>" 
     SelectCommand="SELECT [ID], [Name] FROM [Authors] ORDER BY [Name]"></asp:SqlDataSource>     
</EditItemTemplate> 
</asp:TemplateField>  

但我怎麼指定所選的值,我怎麼保存編輯後選定的價值?

+0

做到在RowDataBound事件GridView,然後在RowUpdating事件中,你可以得到選擇的值

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { DropDownList DropDownList1 = (DropDownList)e.Row.FindControl("DropDownList1"); DropDownList1.SelectedValue = "SomeID"; } 

,並獲得選擇的值,我使用RowEditing嘗試事件,但是當發生此事件時,下拉列表不存在於單元的控件集合中。 – 2011-04-03 10:44:12

+0

我也試過'/>,但ASP.NET說DropDownList中沒有SelectedItemValue屬性,雖然有一個! – 2011-04-03 10:53:26

回答

2

您需要通過

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) 
{ 
    DropDownList DropDownList1 = (DropDownList)this.GridView1.Rows[e.RowIndex].FindControl("DropDownList1"); 
    string value = DropDownList1.SelectedValue; 
} 
+0

謝謝,@Waqas Raja!我可以使用GridView1_RowDataBound設置下拉列表選定的項目,但我認爲更新應該以不同的方式完成。此外,你的第二段代碼不起作用。 – 2011-04-03 11:02:44

+1

正確的RowUpdating處理程序是:protected void DropDownList DropDownList1 =(DropDownList)this.GridView1.Rows [e.RowIndex] .FindControl(「DropDownList1」); e.NewValues.Add(「AuthorID」,DropDownList1.SelectedValue); – 2011-04-03 11:07:41

+0

@ Bogdan0x400,感謝您的意見,是的,你是對的應該有一些不同的方式來獲取選定的值更新時。我相應地更正了我的代碼。 – 2011-04-03 11:51:53