要在DataGrid中動態綁定DropDownList,可以通過以下步驟實現:
<asp:DataGrid ID="myDataGrid" runat="server">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:DropDownList ID="myDropDown" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
protected void myDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// 獲取當前行的數據
DataRowView rowView = (DataRowView)e.Item.DataItem;
// 找到DropDownList控件
DropDownList ddl = (DropDownList)e.Item.FindControl("myDropDown");
// 設置DropDownList的數據源
ddl.DataSource = GetDropDownListData(rowView);
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataBind();
}
}
private DataTable GetDropDownListData(DataRowView rowView)
{
// 根據需要獲取數據源
DataTable dt = new DataTable();
// ...
return dt;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
myDataGrid.DataSource = GetGridData();
myDataGrid.DataBind();
}
}
上述步驟中,通過在DataGrid的模板列中添加DropDownList控件,并在OnItemDataBound事件中動態綁定數據源,實現了在DataGrid中動態綁定DropDownList的功能。