Charkins12
Charkins12

Reputation: 190

Asp.net DropdownList source has values but throwing null exception

When stepping through the code, it fails on the "fUserSelect" line saying "Object reference not set to an instance of an object", but arrUsers is obviously populated so I'm at a loss here.

Any extra eyes on this would be wonderful!

Aspx set up:

<label for="fUser">User<span class="tip required">*</span></label>
<div class="group">
    <span class="data dropdown">
        <asp:DropDownList runat="server" ID="fUserSelect" EnableViewState="false"/>
    </span>
</div>

CS:

List<KeyValuePair<string, string>> arrUsers = new List<KeyValuePair<string, string>>(){
        new KeyValuePair<string, string>("1", "Test"),
        new KeyValuePair<string, string>("2", "Test2")
    };
    fUserSelect.DataValueField = "Key";
    fUserSelect.DataTextField = "Value";
    fUserSelect.DataSource = arrUsers;
    fUserSelect.SelectedIndex = 0;
    fUserSelect.DataBind();

Upvotes: 2

Views: 434

Answers (2)

Charkins12
Charkins12

Reputation: 190

After some digging it turns out in my @ page declaration, my Inherits = "control page name" was referencing another control. Turned out to be a copy paste error. This question / answer helped me solve the issues.

I posted this as my answer, but I was also making a new instance of the control on pageload, I ended up giving my control an ID name and using that as the reference and not looking at a new instance of it.

Upvotes: 0

Sunil Kumar
Sunil Kumar

Reputation: 3242

I have using the below code for binding DropdownList using Dictionary object. Please refer below code:

    Dictionary<string, string> list = new Dictionary<string, string>();
    list.Add("item 1", "Item 1");
    list.Add("item 2", "Item 2");
    list.Add("item 3", "Item 3");
    list.Add("item 4", "Item 4");

    ddl.DataSource = list;
    ddl.DataTextField = "Value";
    ddl.DataValueField = "Key";
    ddl.DataBind(); 

I hope it helps you.

If you want to follow your code then I you have to bind DataSource first before binding DataTextField and DataValueField.

Change your code like below :

        List<KeyValuePair<string, string>> arrUsers = new List<KeyValuePair<string, string>>(){
            new KeyValuePair<string, string>("1", "Test"),
            new KeyValuePair<string, string>("2", "Test2")
        };
        fUserSelect.DataSource = arrUsers;
        fUserSelect.DataValueField = "Key";
        fUserSelect.DataTextField = "Value";           
        fUserSelect.SelectedIndex = 0;
        fUserSelect.DataBind();

Thanks.

Happy Coding

Upvotes: 1

Related Questions