Why are DropDownList data bound to <String> not working?

I am trying to bind List<String>to DropDownListin a user control. I think I am doing the right thing, but it seems that after my code, the bindings are erased . Here is the code for the review!

User control:

<asp:DropDownList ID="subjectNameDropDown" runat="server"/>
<asp:DropDownList ID="yearLevelDropDown" runat="server"/>

Automatically generated code:

public partial class NewSiteMetadataUserControl {
    protected global::System.Web.UI.WebControls.DropDownList subjectNameDropDown;
    protected global::System.Web.UI.WebControls.DropDownList yearLevelDropDown;
}

Code for:

public partial class NewSiteMetadataUserControl : UserControl
{
    protected override void CreateChildControls()
    {
        subjectNameDropDown = new DropDownList();
        yearLevelDropDown = new DropDownList();
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        EnsureChildControls();

        // Attempt 1
        List<String> subjectNames = GetSubjectValues();
        foreach (var subjectName in subjectNames)
            subjectNameDropDown.Items.Add(subjectName);
        subjectNameDropDown.DataBind();

        // Attempt 2
        List<String> yearLevels = GetYearLevelValues();
        yearLevelDropDown.DataSource = yearLevels;
        yearLevelDropDown.DataBind();
    }
}

Should this approach work?

If so, how can I debug what happens after the code runs?

+3
source share
2 answers

CreateChildControls. - , . , , , OnLoad.

, EnsureChildControls.

0

, , ,

  • DropDownList, DataBind, DataSource. №1 .
  • List<string>, / . List<Person> () .ToString() Person / DataTextField, DataValueField.
  • ASP.NET / string.

, HTML . / ? .

"" ( , ), Dictionary<TKey,TValue>.

, .

+1

Source: https://habr.com/ru/post/1770841/


All Articles