How to Set the Default Value of a DropDownList in an ASP.NET Page

(Using Membership ObjectDataSource From MSDN Article)

I’m doing a project where I have lots of DropDownList’s on a page and want a simple way to set the initial values based on some known value.  The DropDownLists are retrieved using ObjectDataSource but I don’t want the first value displayed.  I wrestled some with how to do this using page_load or page_prerender but didn’t come up with good solutions.  I did finally
decide that programming the databound event of the dropdownlist was probably the best way to go.

The solution is pasted below.  The MembershipUtilities.MembershipODS c# code can be downloaded from MSDN or on my web site at the following location. 

http://peterkellner.net/2006/01/09/microsoft-aspnet-20-memberrole-management-with-iis/.


<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC-//W3C//DTD XHTML 1.0 Transitional//EN”

  “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>

<script runat=”server>
    protected void DropDownListUser_DataBound(object sender, EventArgs e)

    {
        DropDownListUser.SelectedIndex =
          DropDownListUser.Items.IndexOf
          (DropDownListUser.Items.FindByValue(Context.User.Identity.Name));
    }
</script>
 
<html xmlns=”http://www.w3.org/1999/xhtml>
<head runat=”server>
    <title>DropDownList Initialize</title>
</head>
<body>
    <form id=”form1runat=”server>
    <div>
        <asp:DropDownList ID=”DropDownListUserrunat=”serverDataSourceID=”ObjectDataSourceUserDataTextField=”UserNameDataValueField=”UserNameOnDataBound=”DropDownListUser_DataBound>
        </asp:DropDownList>
        <asp:ObjectDataSource ID=”ObjectDataSourceUserrunat=”serverSelectMethod=”GetMembersTypeName=”MembershipUtilities.MembershipUserODS>
            <SelectParameters>
                <asp:Parameter Name=”sortDataType=”String/>
            </SelectParameters>
        </asp:ObjectDataSource>
    </div>
    </form>
</body>
</html>
About Peter Kellner

Follow me:


Comments

  1. peter’s solution is working properly.
    it’s working

  2. Hi,

    I’ve got a similar problem. I contruct this list :

    data = TechnicienMgr.GetTechsOfGroupe(idGroupe);

    lstTechniciens.DataSource = data;
    lstTechniciens.DataValueField = “UTCLEUNIK”;
    lstTechniciens.DataTextField = “NOM_PRENOM”;
    lstTechniciens.DataBind();

    and i want to select by default the item where “UTCLEUNIK” = “6545”

    Can you help me ?

  3. Just found this approach, it works great for me:

    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf( DropDownList1.Items.FindByText( defaultText));

    Vía http://techbrij.com/627/select-item-aspdotnet-dropdownlist-programmatically

  4. I found your blog via google and am so glad I did! I’m doing exactly the same thing you are but for myself, not for a book … so you can bet I’ll be returning often!

  5. kiruthika says:

    yes.. peter’s solution is working properly.

  6. gand tari mani

  7. uiiiiiiiiiiiiiiiii

  8. Thank you. it is working properly.

  9. Peter’s solution is perfect as compare to other solutions because the only solution works for me is his solution when i used it with sharepoint web parts or other update panel cotainers.

  10. I like almost everyones solutions better than mine. I just had to do this again in codecamp project for speakers picking shirt sizes and this is what I ended up with. Very similar to others:

    ListItem listItem = DropDownListSpeakerShirtSize.Items.FindByValue(Attendee.ShirtSize);
    if (listItem != null)
    {
    DropDownListSpeakerShirtSize.SelectedValue = listItem.Value;
    }

  11. Hi, although its a bit old now thanks for the above discussion as it lead me towards my solution. The problem is I wanted a dropdownlist to default to a specific value not the first in the list (from my database) and using:-

    protected void Page_Load(object sender, EventArgs e)
    {
    maxCostDDList.SelectedValue = “1500”;
    }

    just set the dropdown list to 1500 every time the page was submitted, not good. But thanks to suggestions on here this worked for me:-

    protected void maxCostDDList_DataBound(object sender, EventArgs e)
    {
    if (maxCostDDList.Items.FindByValue(“1500″) != null)
    {
    maxCostDDList.SelectedValue = “1500”;
    }
    }

    did try “-1″ but that didn’t work for me.

    Cheers to all.

  12. How can assign a item to dropdownlist in runtime..

    that dropdownlist already loaded with somevalue like jan,feb,mar,apr

    i want to assgin a value feb at runtime…

    how can i assogn it…

  13. You could easily set the value of the drop down list . Either using code or
    directly in the aspx file.

    </

    Read More
    http://muruganad.com/ASP.NET/ASP_.NET_Drop_Down_List_Default_Value.html

    Thanks!
    Murugan Andezuthu Dharmaratnam

  14. Correction – The above worked for FF but not for IE (I’ve no idea why since its server side code) Anyway the below worked for both

    protected void DropDownListOrg_DataBound(object sender, EventArgs e)
    {
    if (DropDownListOrg.Items.FindByValue(“-1″) != null)
    DropDownListOrg.SelectedValue = “-1″;
    }

  15. I recommend a mixture of the abpve methods. This way you get the default value and protect against exceptions

    protected void Page_Load(object sender, EventArgs e)
    {
    if (DropDownListOrg.Items.FindByValue(“-1″) != null)
    DropDownListOrg.SelectedValue = “-1″;
    }

  16. in the Page_Load method in the code behind for my apsx page I added this to set the initial value of a drop down list:

    protected void Page_Load(object sender, EventArgs e)
    {
    v_state.SelectedValue = “AK”;
    }

  17. I’m not sure how, but I’m sure you could do it client side. -Peter

  18. jjsoriano says:

    I see no reason why you need to do it in server side. is there anyway to do it in the client side?

  19. Be careful.
    DropDownListUser.Items.FindByValue(Context.User.Identity.Name) may return null. When it does, you may get “object is not an instance” exception.

  20. I use Naveen’s approach too but at run time when databind occurs, if the SelectedIndex is not cleared to -1 first then you can get an http error that you cannot have more than one item selected. It goes something like
    DropDownList.SelectIndex = -1;
    DropDownListUser.Items.FindByValue(Context.User.Identity.Name).Selected = true;

  21. I agree with NaveenJ. His approach is just want i’m using :p

  22. I dont agree with george, since it replaces the selectedvalue.
    But Peter
    why cant we use
    DropDownListUser.Items.FindByValue(Context.User.Identity.Name).Selected = true;
    is it not more simpler?

  23. Why you don’t use just

    DropDownListUser.SelectedValue = Context.User.Identity.Name;

    instead of

    DropDownListUser.SelectedIndex =
    DropDownListUser.Items.IndexOf(
    DropDownListUser.Items.FindByValue(Context.User.Identity.Name));

    ?

Trackbacks

  1. […] Hi, although its a bit old now thanks for the above discussion as it lead me towards my solution. The problem is I wanted a dropdownlist to default to a specific value not the first in the list (from my database) and using:- – read more […]

Your Comments

*

Protected with IP Blacklist CloudIP Blacklist Cloud

Follow

Get every new post delivered to your Inbox

Join other followers: