• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 607
  • Last Modified:

Adding a default value to a drop down list that is databound in ASP.

Still new to ASP.
I'm making a dynamic e-commerce website for auto parts that allows users to choose a year, make, and model part, then options for the part.  All information is dynamically bound to my SQL server.  I have all the SQL working the way I want it, but the drop down lists in ASP select default value from the drop down list when the page loads. Some of the data sources are stored procedures.

 I'm looking to do two things:

First, I want a default value (such as Select A Year) to be the default choice in the drop down list WITHOUT adding it into the database the drop down list it is bound to (Our main business runs off these databases as well and I do not want to add anything to it).  I also want this to have no selected value, so it does not attempt to pass "Select A Year" onto the next page.

Second, I need the Year, Make, Model, Part Type, and options chosen in that order.  I'd like the other options to appear, but I want them to be locked until the previous option is chosen.

I've been searching for a long time on how to do this, and can't really find anything.  I appreciate any help.  Full code and code behind below.  If I need to provide anymore information, please let me know.


<body>
    <form id="form1" runat="server">
    <div>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:PowerlinkConnectionString %>"
            SelectCommand="&#13;&#10;SELECT DISTINCT(ModelYear), 'Select A Year'&#13;&#10;FROM dbo.CARLINE&#13;&#10;WHERE ModelYear > '1980' AND ModelYear < YEAR(GETDATE()) + 2&#13;&#10;ORDER BY ModelYear DESC&#13;&#10;">
        </asp:SqlDataSource>
        &nbsp;
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:SapDBConnectionString %>"
            SelectCommand="sp_GetMakesForYear" SelectCommandType="StoredProcedure">
            <SelectParameters>
                <asp:ControlParameter ControlID="YearDropDownList" Name="ModelYear" PropertyName="SelectedValue"
                    Type="Int32" />
            </SelectParameters>
        </asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:SapDBConnectionString %>"
            SelectCommand="SP_GetModelsForMakes" SelectCommandType="StoredProcedure">
            <SelectParameters>
                <asp:ControlParameter ControlID="YearDropDownList" Name="ModelYear" PropertyName="SelectedValue"
                    Type="Int32" />
                <asp:ControlParameter ControlID="MakeDropDownList" Name="Make" PropertyName="SelectedValue"
                    Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:SapDBConnectionString %>"
            SelectCommand="SELECT [Description], [PartType] FROM [Part_Type] ORDER BY [Description]"></asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:SapDBConnectionString %>"
            SelectCommand="SP_FindPartsByYearModel" SelectCommandType="StoredProcedure">
            <SelectParameters>
                <asp:ControlParameter ControlID="PartDropDownList" Name="PartTypeNbr" PropertyName="SelectedValue"
                    Type="String" />
                <asp:ControlParameter ControlID="YearDropDownList" Name="CarlineYear" PropertyName="SelectedValue"
                    Type="Int16" />
                <asp:ControlParameter ControlID="ModelDropDownList" Name="CarlineNm" PropertyName="SelectedValue"
                    Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
        &nbsp;
        <br />
   
    </div>
        <asp:DropDownList ID="YearDropDownList" runat="server" DataSourceID="SqlDataSource1"
            DataTextField="ModelYear" DataValueField="ModelYear" OnSelectedIndexChanged="YearDropDownList_SelectedIndexChanged" AutoPostBack="True" OnInit="Page_Load" >
        </asp:DropDownList>
       
        <asp:DropDownList ID="MakeDropDownList" runat="server" DataSourceID="SqlDataSource2"
            DataTextField="Make" DataValueField="Make" OnSelectedIndexChanged="MakeDropDownList_SelectedIndexChanged" AutoPostBack="True" OnPreRender="YearDropDownList_SelectedIndexChanged">
         </asp:DropDownList>
        <asp:DropDownList ID="ModelDropDownList" runat="server" DataSourceID="SqlDataSource3"
            DataTextField="TrueModel" DataValueField="HollanderModel" OnSelectedIndexChanged="ModelDropDownList_SelectedIndexChanged" AutoPostBack="True" OnPreRender="MakeDropDownList_SelectedIndexChanged">
        </asp:DropDownList>
        <asp:DropDownList ID="PartDropDownList" runat="server" DataSourceID="SqlDataSource4"
            DataTextField="Description" DataValueField="PartType" OnSelectedIndexChanged="PartDropDownList_SelectedIndexChanged" AutoPostBack="True" OnPreRender="ModelDropDownList_SelectedIndexChanged">
            <asp:ListItem></asp:ListItem>
        </asp:DropDownList>
        <asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource5"
            DataTextField="Application" DataValueField="InventoryNbr" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
        </asp:RadioButtonList>
        <asp:Button ID="SubmitButton" runat="server" OnClick="SubmitButton_Click" Text="FindParts" /><br />
    </form>


-----Code Behind

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {



    }
    protected void YearDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }
    protected void MakeDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }
    protected void ModelDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }
    protected void PartDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

0
reedsster1
Asked:
reedsster1
  • 6
  • 3
2 Solutions
 
urir10Commented:
for a default value you can add something like this in the page_load event

        ddlName.Items.Insert(0, new ListItem("Select A Year", "0"));
        ddlName.SelectedValue = "0";

as for the second question, do you just need to disable the ddl's until the one above it is selected?
if so just set them all as enabled false and then in the SelectedIndexChanged event set the below ddl to enabled true.

Just make sure you set AutoPostback of the dropdown list to True
0
 
reedsster1Author Commented:
So I add something like this, which is what I think you were suggesting:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        YearDropDownList.Insert(0, new ListItem("Select A Year", "0"));
        YearDropDownList.SelectedValue = "0";

    }
    protected void YearDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }
    protected void MakeDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }
    protected void ModelDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }
    protected void PartDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }


    protected void SubmitButton_Click(object sender, EventArgs e)
    {

        string INVNUM = RadioButtonList1.SelectedValue;
        string YEAR = YearDropDownList.SelectedValue;
        string MAKE = MakeDropDownList.SelectedValue;
        string MODEL = ModelDropDownList.SelectedValue;
        string PARTTYPE = PartDropDownList.SelectedValue;
        Response.Redirect("~/PartSearch.aspx?INVNUM=" + INVNUM + "&YEAR=" + YEAR + "&MAKE=" + MAKE + "&MODEL=" + MODEL +  "&PARTTYPE=" + PARTTYPE);
    }

}


And I get the error

Error      1      'System.Web.UI.WebControls.DropDownList' does not contain a definition for 'Insert'      C:\Documents and Settings\SRESPECKI\My Documents\Visual Studio 2005\WebSites\WebSite17\PartLookup.aspx.cs      17      26      C:\...\WebSite17\

Did I mis-understand you or do it wrong?
0
 
reedsster1Author Commented:
Looks like I made a mistake and took of the part of your solution.  I tried it again with:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        YearDropDownList.Items.Insert(0, new ListItem("Select A Year", "0"));
        YearDropDownList.SelectedValue = "0";


    }
    protected void YearDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }
    protected void MakeDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }
    protected void ModelDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }
    protected void PartDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }


    protected void SubmitButton_Click(object sender, EventArgs e)
    {

        string INVNUM = RadioButtonList1.SelectedValue;
        string YEAR = YearDropDownList.SelectedValue;
        string MAKE = MakeDropDownList.SelectedValue;
        string MODEL = ModelDropDownList.SelectedValue;
        string PARTTYPE = PartDropDownList.SelectedValue;
        Response.Redirect("~/PartSearch.aspx?INVNUM=" + INVNUM + "&YEAR=" + YEAR + "&MAKE=" + MAKE + "&MODEL=" + MODEL +  "&PARTTYPE=" + PARTTYPE);
    }


}

And get a new error:

'YearDropDownList' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value


Also, I was able to follow your advise on how to disable the dependent DDL's and set their new SelectedIndexChanged accordingly.  I do not see where it actually enables it?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
jeyan10Commented:
Hi,

Try using the following code in ur pageload

if(!Page.IsPostBack)
{
       YearDropDownList.Items.Insert(0, new ListItem("Select A Year", "0"));
        YearDropDownList.SelectedValue = "0";
}
0
 
reedsster1Author Commented:
Getting the same error:

Server Error in '/WebSite17' Application.
--------------------------------------------------------------------------------

'YearDropDownList' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentOutOfRangeException: 'YearDropDownList' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace:


[ArgumentOutOfRangeException: 'YearDropDownList' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value]
   System.Web.UI.WebControls.ListControl.PerformDataBinding(IEnumerable dataSource) +977
   System.Web.UI.WebControls.ListControl.OnDataBinding(EventArgs e) +101
   System.Web.UI.WebControls.ListControl.PerformSelect() +21
   System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +71
   System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +61
   System.Web.UI.WebControls.BaseDataBoundControl.OnPreRender(EventArgs e) +22
   System.Web.UI.WebControls.ListControl.OnPreRender(EventArgs e) +19
   System.Web.UI.Control.PreRenderRecursiveInternal() +91
   System.Web.UI.Control.PreRenderRecursiveInternal() +180
   System.Web.UI.Control.PreRenderRecursiveInternal() +180
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3873

 


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.3603; ASP.NET Version:2.0.50727.3082
0
 
urir10Commented:
Thats wired, i tried it on my code and it loaded the first item fine with no error. Can you run the app in debug mode and check the values of the ddl on page load and report back.

As for the second question. To enable the ddl's one after another is simple. You write the code that enables the next ddl in the SelectedIndexChanged event of the previous ddl.
so for example:

  protected void YearDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        MakeDropDownList.Enabled= true;
    }
    protected void MakeDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
       ModelDropDownList.Enabled= true;
    }
    protected void ModelDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        and so on.....
    }
0
 
reedsster1Author Commented:
Well that works for the second part kind of, but it brings me back to my original problems.  As soon as the page loads, there is data in the DDL's and it activates all the other DDL's.  I need it to display a prompt text that doesn't have any value to activate the next control.  I'll run the debugger and post it.
0
 
reedsster1Author Commented:
Can't get anything to show on the debug.  When I change the code to look like this:

        if (!Page.IsPostBack)
        {
            YearDropDownList.Items.Insert(0, new ListItem("Select A Year", "2000"));
            YearDropDownList.SelectedValue = "2000";
        }
It does display 2000 as the default value.  I think the problem is that before it was set to 0, when my data range is only 1980-2000 .  It still isn't starting out with "Select A Year" as the prompt text.  I'd assume that this is because the data source it's pulling from is an int data source?  Any suggestions?
0
 
urir10Commented:
I think what happens is that it binds the data from the database after the pageload event and overrides your custom insert. Set the property AppendDataBoundItems="true" for the ddl.

As for the selectedindex changed event, include an if statement to check if the selected index is greater than 0 ( meaning something else other than the default value was selected ) and only then enable the next ddl.
0
 
reedsster1Author Commented:
Fixed both my problems!
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

  • 6
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now