[英]Dropdown List not adding Items
I am working on implementing a DropDownList
for a website (not my own website) and I can not get the DropDownList
to populate any items.我正在为网站(不是我自己的网站)实施
DropDownList
,但我无法让DropDownList
填充任何项目。 Bit frustrating but that's the life of a coder right?有点令人沮丧,但这就是编码员的生活,对吗? This is what I have for the code so far regarding the
DropDownList
.到目前为止,这是关于
DropDownList
的代码。 I have an understanding of C# but aspx and the bridge between them is new to me so I might of missed something obvious.我了解 C# 但 aspx 和它们之间的桥梁对我来说是新的,所以我可能会错过一些明显的东西。 Could someone steer me in the right direction?
有人可以引导我朝着正确的方向前进吗?
aspx file's DropDown Generation aspx 文件的下拉生成
<asp:DropDownList runat="server" ID="dpdCategory" Width="200px"/>
Init to ID in .cs file初始化为 .cs 文件中的 ID
protected DropDownList dpdCategory;
Function to Generate the Items生成项目的函数
protected void Page_Load(object sender, EventArgs e)
{
this.dpdCategory.Items.Clear();
this.dpdCategory.Items.Add(new ListItem("hello", "0"));
this.dpdCategory.Items.Add(new ListItem("hello", "1"));
}
You might need to put it when the page is not posting back.您可能需要在页面未回发时放置它。 Like this:
像这样:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
this.dpdCategory.Items.Clear();
this.dpdCategory.Items.Add(new ListItem("hello", "0"));
this.dpdCategory.Items.Add(new ListItem("hello", "1"));
}
}
var categories = new List<ListItem>
{
new ListItem("hello", "0"),
new ListItem("hello", "1")
};
dpdCategory.DataTextField = "Text";
dpdCategory.DataValueField = "Value";
dpdCategory.DataSource = categories ;
dpdCategory.DataBind();
You dont have to initialise dropdownlist in .cs file.您不必在 .cs 文件中初始化下拉列表。
Then change your page load like this:然后像这样更改页面加载:
protected void Page_Load(object sender, EventArgs e)
{
dpdCategory.Items.Clear();
dpdCategory.Items.Add(new ListItem("hello", "0"));
dpdCategory.Items.Add(new ListItem("hello", "1"));
}
This should work.这应该有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.