2011-04-03 40 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