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. Bit frustrating but that's the life of a coder right? This is what I have for the code so far regarding the 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. Could someone steer me in the right direction?
aspx file's DropDown Generation
<asp:DropDownList runat="server" ID="dpdCategory" Width="200px"/>
Init to ID in .cs file
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.