Asp.net

如何在gridview中綁定下拉列表?

  • December 12, 2018

我有一個gridview,其中每一行都包含一個下拉列表。我想動態綁定每個下拉列表。有人可以告訴我我該怎麼做。提前致謝

如果您使用的是模板列,那麼您可以使用數據綁定表達式從標記中綁定下拉列表。例如,

<asp:TemplateField HeaderText="XYZ">
 <ItemTemplate>
   <asp:DropDownList runat="server" ID="MyDD" DataSourceId="MyDataSource" />
 </ItemTemplate> 
</asp:TemplateField>

以上假設您的下拉數據在各行中保持不變。如果它正在發生變化,那麼您可以使用數據綁定表達式,例如

<asp:DropDownList runat="server" DataSource='<%# GetDropDownData(Container) %>' DataTextField="Text" DataValueField="Value"  />

GetDropDownData 將是程式碼隱藏中的受保護方法,它將返回給定行的數據(數據表、列表、數組)。

您可以在程式碼隱藏中使用GridView.RowDataBound事件(或 RowCreated 事件)來填充下拉列表。例如,

 protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
 {

   if(e.Row.RowType == DataControlRowType.DataRow)
   {
     // Find the drop-down (say in 3rd column)
     var dd = e.Row.Cells[2].Controls[0] as DropDownList;
     if (null != dd) {
        // bind it
     }

     /*
     // In case of template fields, use FindControl
     dd = e.Row.Cells[2].FindControl("MyDD") as DropDownList;
     */
   }

 }

引用自:https://stackoverflow.com/questions/7329224