Asp.net - Add blank item at top of dropdownlist

后端 未结 10 1801
甜味超标
甜味超标 2020-11-30 20:03

Why is the dropdown not showing my blank item first? Here is what I have

drpList.Items.Add(New ListItem(\"\", \"\"))

With drpList
    .DataSource = myContro         


        
相关标签:
10条回答
  • 2020-11-30 20:14

    The databinding takes place after you've added your blank list item, and it replaces what's there already, you need to add the blank item to the beginning of the List from your controller, or add it after databinding.

    EDIT:

    After googling this quickly as of ASP.Net 2.0 there's an "AppendDataBoundItems" true property that you can set to...append the databound items.

    for details see

    http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=281 or

    http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx

    0 讨论(0)
  • 2020-11-30 20:15

    After your databind:

    drpList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
    drpList.SelectedIndex = 0;
    
    0 讨论(0)
  • 2020-11-30 20:18

    Do your databinding and then add the following:

    Dim liFirst As New ListItem("", "")
    drpList.Items.Insert(0, liFirst)
    
    0 讨论(0)
  • 2020-11-30 20:23

    it looks like you are adding a blank item, and then databinding, which would empty the list; try inserting the blank item after databinding

    0 讨论(0)
  • 2020-11-30 20:24

    You could also have a union of the blank select with the select that has content:

    select '' value, '' name
    union
    select value, name from mytable
    
    0 讨论(0)
  • 2020-11-30 20:27

    I think a better way is to insert the blank item first, then bind the data just as you have been doing. However you need to set the AppendDataBoundItems property of the list control.

    We use the following method to bind any data source to any list control...

    public static void BindList(ListControl list, IEnumerable datasource, string valueName, string textName)
    {
        list.Items.Clear();
        list.Items.Add("", "");
        list.AppendDataBoundItems = true;
        list.DataValueField = valueName;
        list.DataTextField = textName;
        list.DataSource = datasource;
        list.DataBind();
    }
    
    0 讨论(0)
提交回复
热议问题