How to set DropdownList Initial selectedIndex

Last post 10-13-2007 11:49 PM by PeterBrunone. 14 replies.

Sort Posts:

  • How to set DropdownList Initial selectedIndex

    05-01-2006, 10:17 AM
    • Loading...
    • clflyer
    • Joined on 03-15-2006, 5:28 PM
    • Midwest
    • Posts 38

    I have a form with a dropdownlist named ddlCustomer. When the page loads I want to set the selectedindex to the 1st item in my ddl and then call a routine that updates the form to the data for that customer. I have tried the following code, but the ddl selectedindex remains at -1. How do I get this to change?

    If Not Page.IsPostBack Then
       'Popuulate the form with the 1st Customer's data
       ddlCustomer.SelectedIndex = 0
       ddlCustomer_SelectedIndexChanged(
    Nothing, Nothing
    )
    End If
  • Re: How to set DropdownList Initial selectedIndex

    05-01-2006, 11:09 AM
    • Loading...
    • encapsul2
    • Joined on 04-26-2006, 9:10 PM
    • San Francisco
    • Posts 202

    Could you clarify what you are trying to accomplish?  You might want to just pass in the value of first list item to the sub.  Something like:

    ddlMySub(ddlCustomer.items(0).value.tostring))

    If you are looking for the actual "selectedIndexChanged" event you will need to create that outside of the onload.

     

    cheers

    Matthew


    Performance Outlook
  • Re: How to set DropdownList Initial selectedIndex

    05-01-2006, 11:19 AM
    • Loading...
    • clflyer
    • Joined on 03-15-2006, 5:28 PM
    • Midwest
    • Posts 38

    The subroutine ddlCustomer_SelectedIndexChanged has all the code to populate a form with the selected index value. I simply want to be able to open the form and have it populate the form with the 1st record of the ddl.

    I want to do this on the 1st opening of the form. When I try stepping through the code, the selectedIndex is always -1 in Page_Load. Is there another Page event that I should be using?

  • Re: How to set DropdownList Initial selectedIndex

    05-01-2006, 12:18 PM
    • Loading...
    • encapsul2
    • Joined on 04-26-2006, 9:10 PM
    • San Francisco
    • Posts 202

    A selectedIndex of -1 indicates "no selection" and you should refer to the items location in the collection vs. the user selected index.

    so the line ddlMyDropDownList.items(0).value and ddlMyDropDownList.items(0).text will provide the first items in your dropdown AFTER you populate the list but BEFORE a user gets to make a selection. 

     

    Hope this helps

     

    Matthew

    engineer
    PerformanceOutlook
    http://www.performanceOutlook.com

    cheers

    Matthew


    Performance Outlook
  • Re: How to set DropdownList Initial selectedIndex

    05-01-2006, 12:56 PM
    • Loading...
    • clflyer
    • Joined on 03-15-2006, 5:28 PM
    • Midwest
    • Posts 38

    I tried what you suggested, but I get the following error:

    Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
       'Use the 1st Item in the Customer list to populate the form
       
    If Not Page.IsPostBack Then
          
    'Populate the form with the 1st Customer's data
          
    PopulateForm(Me.ddlCustomer.Items(0).Value)
       End If
    End Sub

    The error occurs on the Green line in the code above. The ddl is populated by a SqlDataSource. Could the problem be that it hasn't loaded the ddl yet? I tried the code at Page_LoadComplete and got the same error.

  • Re: How to set DropdownList Initial selectedIndex

    05-01-2006, 12:57 PM
    • Loading...
    • clflyer
    • Joined on 03-15-2006, 5:28 PM
    • Midwest
    • Posts 38
    Oops, the green line lost it's formatting. The green line is the call to the subroutine PopulateForm
  • Re: How to set DropdownList Initial selectedIndex

    05-01-2006, 2:34 PM
    • Loading...
    • encapsul2
    • Joined on 04-26-2006, 9:10 PM
    • San Francisco
    • Posts 202
    Please show me the code when/where you populate the DropDown. 
    cheers

    Matthew


    Performance Outlook
  • Re: How to set DropdownList Initial selectedIndex

    05-01-2006, 2:40 PM
    • Loading...
    • clflyer
    • Joined on 03-15-2006, 5:28 PM
    • Midwest
    • Posts 38

    <asp:CheckBox ID="Dirty" runat="server" BackColor="#FFFFC0" Visible="False" />
    <
    asp:
    DropDownList
    ID="ddlCustomer" runat="server" AutoPostBack="True"      DataSourceID
    ="SqlCustomers"
    DataTextField="Customer" DataValueField="customernumber"></asp:DropDownList
    >
    <
    asp:SqlDataSource ID="SqlCustomers" runat="server" ConnectionString="<%$ ConnectionStrings:Test_CustomerConnectionString %>
    "

    My connection string follows:
    <add name="Test_CustomerConnectionString" connectionString="Data Source=MATRIX001\MATRIX001;Initial Catalog=Test_Customer;Integrated Security=True" providerName="System.Data.SqlClient" />

  • Re: How to set DropdownList Initial selectedIndex

    05-01-2006, 2:55 PM
    • Loading...
    • encapsul2
    • Joined on 04-26-2006, 9:10 PM
    • San Francisco
    • Posts 202

    OK,

    You need to make sure you pull the value AFTER the databind.  I usually declare everything in the code behind for neatness and then databind. Something like:

    WITH ddlCustomer

       .DataSource=" "

       .DataTextField = "Customer"

       .DataValueField = "customernumber"

       .DataBind

    END WITH

    So I am not sure where the DataBind event is occuring in your code.  Try placing a ddlCustomers.databind in the first line of onLoad and see if that works.

     

    cheers

    Matthew


    Performance Outlook
  • Re: How to set DropdownList Initial selectedIndex

    05-01-2006, 3:04 PM
    • Loading...
    • deokule2003
    • Joined on 12-05-2005, 6:09 PM
    • Pune, India
    • Posts 356

    Hello,

    I think you want to set "selected" to dropdownlist control. So it will initially show first value as selected. Refer following link to get more information about it:

    http://aspnet.4guysfromrolla.com/articles/080702-1.3.aspx

    Regards

    Kuldeep Deokule

    MCSD.NET
    Blog: http://dkuldeep.blogspot.com

    This posting is provided "AS IS" with no warranties, and confers no rights.
  • Re: How to set DropdownList Initial selectedIndex

    11-16-2006, 8:03 AM
    • Loading...
    • christo_c
    • Joined on 11-10-2006, 7:10 AM
    • South Africa
    • Posts 5

    This is an old post but I'll reply for other people that reference it, as it is how I stumbled upon it.

    I think I know what your problem is here...

    Although you can set the .SelectedIndex and .SelectedValue properties in Page_Load() it does not get set there when the data is not bound.  It only gets set after DataBind() has been called (In your case probably by a SqlDataSource).  So in your case you would have to call ddlCustomer_SelectedIndexChanged(Nothing, Nothing) in the ddlCustomer_DataBound() event handler (DropDownList.DataBound).

    Here is the code listing of a new component I derived from a DropDownList to get rid of the ugly: "'controlname' has a SelectedValue which is invalid because it does not exist in the list of items." error when assigning a value that's not in the list.  The idea here is that it should go back to the "unassigned" item and not throw an exception.

     New properties:

    • bool AddUnassignedLine - set to true when you always want the unassigned ("please select") line.
    • bool SelectUnassignedLineWhenInvalid - Add and/or select the unassigned line when the abovementioned error occurs.
    • string UnassignedLineText - text for the unassigned line, default = "--Please Select--"
    • string UnassignedLineValue - value for the unassigned line, default = "-1"

    I'm still busy testing it, so I might post updates later. 

    This is my first ASP.NET/.NET/C# component so it might not be perfect. I've only been working with VS2005 for a week now. (coming from Delphi 7)

    For those of you who don't know, here's the steps to create this custom control:

    1.  In VS2005 go File->New->Project and select the Class Library
    2. Type Name and Solution Name at the bottom, click OK.
    3. then to add my stuff: copy all my code and past it over the created .cs file contents
    4. change the namespace if you like
    5. also change "CSEDropDownList" to what you like:     [ToolboxData( "<{0}:CSEDropDownList runat=server></{0}:CSEDropDownList>" )]
          public class CSEDropDownList: System.Web.UI.WebControls.DropDownList
    6. Also add this to the bottom your AssemblyInfo.cs file: [assembly: TagPrefix( "CSEControls", "ddl" )]
    7. AFTER YOU BUILT THE COMP: To register on the Toolbox, right click the toolbox and select Choose Items..., select your new control there, if it's not there, browse for the .dll of your assembly.

     

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace CSEControls
    {
        [ToolboxData( "&lt;{0}:CSEDropDownList runat=server></{0}:CSEDropDownList>" )]
        public class CSEDropDownList: System.Web.UI.WebControls.DropDownList
        {
            private const string constUnassignedLineTextDefault = "--Please Select--";
            private const string constUnAssignedLineValueDefault = "-1";
            private const bool constAddUnassignedLineDefault = false;
    
            [Bindable( true )]
            [Category( "Behavior" )]
            [DefaultValue( constUnassignedLineTextDefault )]
            [Localizable( true )]
            public string UnassignedLineText
            {
                get
                {
                    String s = (String)ViewState["UnAssignedLineText"];
                    return ( ( s == null ) ? constUnassignedLineTextDefault : s );
                }
    
                set
                {
                    ViewState["UnassignedLineText"] = value;
                }
            }
    
            [Bindable( true )]
            [Category( "Behavior" )]
            [DefaultValue( constUnAssignedLineValueDefault )]
            [Localizable( true )]
            public string UnassignedLineValue
            {
                get
                {
                    String s = (String)ViewState["UnassignedLineValue"];
                    return ( ( s == null ) ? constUnAssignedLineValueDefault : s );
                }
    
                set
                {
                    ViewState["UnassignedLineValue"] = value;
                }
            }
    
            [Bindable( true )]
            [Category( "Behavior" )]
            [DefaultValue( constAddUnassignedLineDefault )]
            [Localizable( true )]
            public bool AddUnassignedLine
            {
                get
                {
                    return (bool)( ViewState["AddUnassignedLine"] ?? constAddUnassignedLineDefault );
                }
    
                set
                {
                    ViewState["AddUnassignedLine"] = value;
                }
            }
    
            [Bindable( true )]
            [Category( "Behavior" )]
            [DefaultValue( false )]
            [Localizable( true )]
            public bool SelectUnassignedLineWhenInvalid
            {
                get
                {
                    return (bool)( ViewState["SelectUnassignedLineWhenInvalid"] ?? false );
                }
    
                set
                {
                    ViewState["SelectUnassignedLineWhenInvalid"] = value;
                }
            }
    
            public override string SelectedValue
            {
                get
                {
                    return base.SelectedValue;
                }
                set
                {
                    try
                    {
                        base.SelectedValue = value;
                    }
                    catch ( ArgumentOutOfRangeException ex )
                    {
                        if ( this.SelectUnassignedLineWhenInvalid )
                        {
                            CheckCreateUnassignedLine( true, true );
                            base.SelectedValue = this.UnassignedLineValue;
                            this.DataBind();
                        }
                        else
                            throw ex;
                    }
                }
            }
    
    
            protected override void OnDataBound( EventArgs e )
            {
                base.OnDataBound( e );
            }
    
            protected override void OnDataBinding( EventArgs e )
            {
                try
                {
                    base.OnDataBinding( e );
                    CheckCreateUnassignedLine( false, false );
                }
    
                catch ( ArgumentOutOfRangeException ex )
                {
                    if ( this.SelectUnassignedLineWhenInvalid )
                    {
                        CheckCreateUnassignedLine( true, true );
                        this.SelectedValue = this.UnassignedLineValue;
                    }
                    else
                        throw ex;
                }
            }
    
            private void CheckCreateUnassignedLine( bool ForceCreation, bool ForceSelection )
            {
                if ( ( this.AddUnassignedLine ) || ( ForceCreation ) )
                {
                    if ( ForceSelection )
                        this.ClearSelection();
                    ListItem li;
                    bool bFound = false;
                    // Check if it does not exists already
                    li = this.Items.FindByValue( this.UnassignedLineValue );
                    if ( li != null )
                        if ( li.Text.Equals( this.UnassignedLineText ) )
                            bFound = true;
                    // Create only if not found
                    if ( !bFound )
                    {
                        li = new ListItem( this.UnassignedLineText, this.UnassignedLineValue );
                        this.Items.Insert( 0, li );
                    }
                    // Select if required
                    if ( ForceSelection )
                        li.Selected = true;
                }
            }
    
            protected override void RenderContents( HtmlTextWriter output )
            {
                base.RenderContents( output );
                output.Write( UnassignedLineText );
                output.Write( UnassignedLineValue );
                output.Write( AddUnassignedLine );
                output.Write( SelectUnassignedLineWhenInvalid );
            }
        }
    }
    
     
  • Re: How to set DropdownList Initial selectedIndex

    11-16-2006, 9:32 AM
    • Loading...
    • e_screw
    • Joined on 10-20-2004, 1:22 PM
    • Women, Guitar, Russia, Billiards, Nature, .NET
    • Posts 3,852

    By default the first item of the dropdownlist is selected everytime the page loads, and you can populate the form using

    PopulateForm(ddlCustoms.SelectedItem.Value.ToString());

    Thanks

     

    Mark post(s) as "Answer" that helped you

    Electronic Screw
    Website||Blog||Dub@i.net
  • Re: How to set DropdownList Initial selectedIndex

    10-12-2007, 11:41 AM
    • Loading...
    • salsipius
    • Joined on 05-13-2005, 6:22 AM
    • Posts 37

    I'm not sure if your scenario is the same as mine but you could try this.

     From my query I know what I want the Text of the DDL to be. For instance I want to set the DDL with the users current role Lets say "Manager". I can be sure that manager will be in the list because I used the database to populate the list in the first place.

    Now use the FindByText() method to get the list item that has the text from the database that you want to set the DDL to

    then use the Items.IndexOf to set the index of that listitem.

    ddlRole.SelectedIndex = ( ddlRole.Items.IndexOf( ddlRole.Items.FindByText( user.RoleName )));

    Hope that Helps

  • Re: How to set DropdownList Initial selectedIndex

    10-12-2007, 1:26 PM

    I had the same problem several hours ago and solved it. I think you have to bind the data BEFORE assigning the selectedIndex.

    Use code-behind-scene and do something like this:

                        

    1    list.DataTextField = "textfield"
    2    list.DataValueField = "valfield"
    3    list.DataSource = oDetails.DefaultView