C# dropdown selected item null when list of strings/objects bound to the Data source

北城余情 提交于 2020-01-05 03:56:05

问题


I am trying to bind a List of string to a Dropdown. On frontend, I am able to see the list of dropdown correctly but when I select a value and click on search, it throws a null reference exception because it seems like it is read only. This is what I tried:

<asp:DropDownList runat="server" ID="ddl"  AppendDataBoundItems="True">
<asp:ListItem Value="">Please Select</asp:ListItem></asp:DropDownList>

Code behind:

List<string> items = helper.GetData(); //A method that simply returns a list of strings.

ddl.DataSource = items;
ddl.DataBind();

protected void searchClick(object sender, EventArgs e){

/*This is null and when I inspect this, I don't see any value matching 
the string selected in dropdown.*/
var selectedOption = ddl.SelectedItem.Text;  
}

I tried every possible solution online. I even tried converting it to a dictionary just like it has been given here. I also tried converting it into an object assigning it a title and an ID property as given here

Thank you.


回答1:


You have bind list in dropdownlist but has not append which value has to be fetched when any value got selected.

If(!isPostBack())
{
ddl.DataSource = items;
ddl.DataTextField = "Field name which hold items(Text to be shown in ddl)";
ddl.DataValueField = "ID of items(Value for items)";
ddl.DataBind();
}

If have only list and have to append in dropdown list then use bleow code.

List<string> items=helper.GetData();
for(var i=0; i < items.Count; i++)
{
    ddl.Items.Add(new ListItem(i, items[i]));
    //ddl.Items.Add(new ListItem(key, source)); For reference only
}

To get value you can use:

ddl.SelectedItem.Value;
ddl.SelectedItem.Text;



回答2:


Having a look at this I notice 2 things:

  1. If the first 4 lines are in your page load make sure that you wrap them in a

    if(!isPostBack) {

    }

If it is not wrapped in the !isPostBack then the value will default to the first value every time a postback occurs as the ddl wil get rebound each time.

  1. As mentioned above you are not specifying the DataTextField or DataValueField. If these arent specified you will get object types in the dropdownlist instead of values.

Also, consider using ddl.SelectedValue rather than SelectedItem.Text as this will give you the unique ID assigned to the DataValueField




回答3:


 Dictionary<string, string> openWith = 
        new Dictionary<string, string>(); 

insted of list you need to use following dropdown

ddl.DataSource = items;
ddl.DataTextField = "Text Which Show In DropDown";
ddl.DataValueField = "value -When Text Is Select From Dropdown";
ddl.DataBind();


来源:https://stackoverflow.com/questions/40373004/c-sharp-dropdown-selected-item-null-when-list-of-strings-objects-bound-to-the-da

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!