我的控件中有以下Page_Load方法(System.Web.UI.UserControl):
protected void Page_Load(object sender, EventArgs e)
{
DropDownList ShowAssumptions = new DropDownList();
List<string> list = new List<string>()
{
"test",
"test2"
};
ShowAssumptions.DataSource = from i in list
select new ListItem()
{
Text = i,
Value = i
};
ShowAssumptions.DataBind();
}
然后,在我的.aspx中我有这个:
<asp:DropDownList id="ShowAssumptions" runat="server">
</asp:DropDownList>
但是,DropDownList永远不会被填充。我做错了什么?
答案 0 :(得分:8)
只需将列表指定为数据源即可。另外我假设你不想在每个PostBack上重新加载列表。
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> list = new List<string>()
{
"test",
"test2"
};
ShowAssumptions.DataSource = list;
ShowAssumptions.DataBind();
}
}
答案 1 :(得分:3)
如果你使用 ASP.NET WebForms,EF和Bootstrap 试试这个
<强> HTML 强>
<div class="form-group">
<label class="control-label" for="inputType">Lines: </label>
<asp:DropDownList ID="DropDownListFabricLines" CssClass="dropdown form-control" runat="server"></asp:DropDownList>
</div>
<强> C#强>
var entities = new DababaseEntities();
List<FabricLineView> fabricLines = entities .Line.Select(x=> new FabricLineView { ID = x.LineaID, Name = x.LineaNombre }).ToList();
DropDownListFabricLines.DataValueField = "ID";
DropDownListFabricLines.DataTextField = "Name";
DropDownListFabricLines.DataSource = fabricLines;
DropDownListFabricLines.DataBind();
public sealed class FabricLineView
{
public int ID { get; set; }
public string Name { get; set; }
}
答案 2 :(得分:2)
protected void Page_Load(object sender, EventArgs e)
{
//Don't do this here!
//DropDownList ShowAssumptions = new DropDownList();
List<string> list = new List<string>()
{
"test",
"test2"
};
this.ShowAssumptions.DataSource = from i in list
select new ListItem()
{
Text = i,
Value = i
};
this.ShowAssumptions.DataBind();
}
答案 3 :(得分:1)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
foreach (string item in list)
{
ShowAssumptions.Items.Add(item);
}
}
}