2

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();
Charkins12
  • 190
  • 4
  • 16

2 Answers2

1

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

Sunil Kumar
  • 3,142
  • 1
  • 19
  • 33
0

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.

Community
  • 1
  • 1
Charkins12
  • 190
  • 4
  • 16