我想将数据源添加到下拉列表。此下拉列表是网格视图的列之一。在这里,我想在不使用 sqldatasource 的情况下动态地将数据源添加到下拉列表中。
(vs2008 和 c#)
我想将数据源添加到下拉列表。此下拉列表是网格视图的列之一。在这里,我想在不使用 sqldatasource 的情况下动态地将数据源添加到下拉列表中。
(vs2008 和 c#)
是的,因为它在 itemtemplate 中,所以你不会直接得到它,因为你必须使用 findcontrol
您可以为网格中的下拉列表控件实现 OnDataBinding 事件。如果您可以将 DataSource 属性和其他属性分配给您喜欢的任何内容。将其绑定到一个List<YourObject>
偶数。
在 OnDataBinding 事件上执行此操作还允许您动态自定义 ddl 中的值。因此,如果您需要这种类型的功能,每行的 ddl 可以根据行中的其他一些数据提供一组不同的选项。
如果使用 OnDataBinding 方法而不是自动(简单模式)连线,则 ASP.NET 控件具有大量灵活性。
这是您正在寻找的代码
示例 1:
public enum Color
{
RED,
GREEN,
BLUE
}
每个 Enum 类型都派生自 System.Enum。有两种静态方法可帮助将数据绑定到下拉列表控件(并检索值)。它们是 Enum.GetNames 和 Enum.Parse。使用 GetNames,您可以绑定到下拉列表控件,如下所示:
protected System.Web.UI.WebControls.DropDownList ddColor;
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
ddColor.DataSource = Enum.GetNames(typeof(Color));
ddColor.DataBind();
}
}
示例 2:
List<Person> myPList = new List<Person>();
Person p1 = new Person();
p1.ID = 1;
p1.Name = "Bob";
p1.Color = "Blue";
Person p2 = new Person();
p2.ID = 2;
p2.Name = "Joe";
p2.Color = "Green";
myPList.Add(p1);
myPList.Add(p2);
this.DropDownList1.DataSource = myPList;
this.DropDownList1.DataTextField = "Color";
this.DropDownList1.DataValueField = "ID";
this.DropDownList1.DataBind();
更完整的练习请看这里: https ://stackoverflow.com/a/9076237/132239
也不要忘记始终将您的答案标记为答案