DropDownList keeps displaying Empty string for SelectedValue

mbarazi
mbarazi used Ask the Experts™
on
I have a C# .net 2.0 page that contains a search functionality. Basically a dropdownlist with a search button.
On the initial pageload event the dropdown gets populated with a datasource and everything works with no errors but after I have selected an item from the dropdown and then clicked search button. The pageload event is triggered first, at this point it seems like my dropdownlist doesn't have a value before I even hit the If(!IsPostBack).
The control is set to AutoPostBack=False. Thanks  
Public class
{
private SortableCollection<SalesRepInfo> _detailsInfoCollection;

protected void Page_Load(object sender, EventArgs e)
        {
           

            if (!IsPostBack)
            {

                _accountManagersList = AccountManager.GetAccountManagerList();  //Pack.GetStandardPackCategories();
                ddlAccountManagerIDFilter.DataSource = _accountManagersList;
                ddlAccountManagerIDFilter.DataBind();
                ddlAccountManagerIDFilter.Items.Insert(0, new ListItem("Select an Account Mgr", String.Empty));
                // this.ddlAccountManagerIDFilter.SelectedIndexChanged += new EventHandler(ddlAccountManagerIDFilter_SelectedIndexChanged);


                ddlAccountManagerIDInsert.DataSource = _accountManagersList;
                ddlAccountManagerIDInsert.DataBind();
                ddlAccountManagerIDInsert.Items.Insert(0, new ListItem("Select an Account Mgr", String.Empty));
                // this.ddlAccountManagerIDInsert.SelectedIndexChanged += new EventHandler(ddlAccountManagerIDInsert_SelectedIndexChanged);

                _productionCoordinatorList = ProductCoordinator.GetProductionCoordinatorList();
                ddlPCIDFilter.DataSource = _productionCoordinatorList;
                ddlPCIDFilter.DataBind();
                ddlPCIDFilter.Items.Insert(0, new ListItem("Select a PrdnCoordinator", String.Empty));
                // this.ddlAccountManagerIDFilter.SelectedIndexChanged += new EventHandler(ddlAccountManagerIDFilter_SelectedIndexChanged);


                ddlPCIDInsert.DataSource = _productionCoordinatorList;
                ddlPCIDInsert.DataBind();
                ddlPCIDInsert.Items.Insert(0, new ListItem("Select a PrdnCoordinator", String.Empty));

            }
            else
            {
                LoadState();
                BindData();
            }
          
        }


Definition of load state 
private void LoadState() 
{
 _detailsInfoCollection = SalesRep.GetSalesRep(txtSalesRepFilter.Text.Trim(), ddlAccountManagerIDFilter.SelectedValue, ddlPCIDFilter.SelectedValue, _quoteRequestApprovalBypass);   //*** At this point I type ?ddlAccountManagerIDFilter.SelectedValue in immediate window and I get nothing "" 
}
}


Here is the ASPX code 
 
                    <table>
                        <tr>
                            <td colspan="2" class="medline_txt_emph" align="center">
                                Search Sales Rep</td>
                        </tr>
                        <tr>
                            <td class="medline_txt_std">
                                Sales Rep:&nbsp;</td>
                            <td>
                                <asp:TextBox ID="txtSalesRepFilter" runat="server" Text="" CssClass="urEdf2TxtEnbl" MaxLength="10" /></td>
                        </tr>
                        <tr>
                            <td class="medline_txt_std">
                                Account Manager ID:&nbsp;</td>
                            <td>
                                <asp:DropDownList  Font-Names ="Lucida Console"  Font-Size="X-Small"  ID="ddlAccountManagerIDFilter" runat="server"  CssClass="medline_dropdownlist"
                                DataValueField="AccountManagerID"  DataTextField="AccountManagerName"  AutoPostBack="False" Width="175px"  /></td>
                        </tr>
                        <tr>
                            <td class="medline_txt_std">
                                PCID:&nbsp;</td>
                            <td>
                                <asp:DropDownList  Font-Names ="Lucida Console"  Font-Size="X-Small"  ID="ddlPCIDFilter" runat="server"  CssClass="medline_dropdownlist"
                                 DataValueField="PCID"  DataTextField="FullName"   AutoPostBack="False" Width="175px"  /></td>
                        </tr>
                        <tr>
                            <td class="medline_txt_std">
                                Quote Request Approval Bypass:&nbsp; 
                            </td>  
                             <td> 
                                <asp:DropDownList ID="ddlRequestApprovalFilter" CssClass="medline_dropdownlist" runat="server" Height="50px"  >
                                    <asp:ListItem Text="All" ></asp:ListItem>
                                    <asp:ListItem Text="No" ></asp:ListItem> 
                                    <asp:ListItem Text="Yes" ></asp:ListItem> 
                                </asp:DropDownList>&nbsp;&nbsp;
                             </td>                      
                        </tr>
                        <tr>
                            <td colspan="2" align="right">
                                <asp:Button ID="btnSearch" runat="server" Text="Search" CssClass="urBtnStd" Height="22px" />
                            </td>
                        </tr>
                        <tr>
                            <td align="left" colspan="2">
                                <asp:ValidationSummary runat="server" ID="valSearchValidationSummary" ValidationGroup="Search"
                                    CssClass="medline_txt_std urTxtCrit" DisplayMode="List" ForeColor="" />
                            </td>
                        </tr>
                    </table>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
You dont have a value for the ListItems, i.e. value="0" etc
Christopher KileSenior Software Analyst

Commented:
You are not setting either the DataTextField or the DataValueField before calling DataBind(), so even though you've specified your data source, no data is actually geting bound to the list.  I don't see how you get a value to display in the list, truthfully, unless your data source is supplying one of the columns as a default value for each list item, and that would only fill the text component of the list item, NOT the value component.

So, you need something like this for each one of your dropdown list controls if you expect .SelectedValue to return anything except Nothing:

               ddlAccountManagerIDFilter.DataSource = _accountManagersList;
               ddlAccountManagerIDFilter.DataTextField = "Field1";
               ddlAccountManagerIDFilter.DataValueField = "Field2";
               ddlAccountManagerIDFilter.DataBind();

Substitute Field1 and Field2 with fields from the data source that represent the text and value you want for the list items in the specified list.

 

Author

Commented:
I have a DataTextField and DataValueField set in the Control's aspx page does that have to be also in the code behind. You see I am populating the Dropdowns using collections which are retrieved from the database. thanks.  
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

ddlRequestApprovalFilter has no values, but not sure if you are checking this one. The other 2 have an insert listitem with a blank value. Which dropdown of the three are you checking which has a blank selectedvalue?

Author

Commented:
I am checking ddlAccountManagerIDFilter and ddlPCIDFilter. But ddlRequestApprovalFilter is carrying the selected value just fine. If I select "ALL" from the drop down it actually comes up on page load if I run the value in immediate window.
I presume you want to do something on the button click - do you have an event for the that to check the values? not sure why you are trying to access them during loadstate?

Author

Commented:
Ok I have removed that part so now I am only doing the binding and setting of data source in pageload and now when I get to btnSearch_Click event I am still with no value for the ddlAccountManagerIDFilter.
I have the controls view state set enableviewstate = true, could I be missing some other property on the control, I will attach the entire aspx page.  It's like the control is not even holding the value once I post back to the server. thanks

<!--%@ PortalComponent name="SalesRepAdmin" %-->
<%@ Control Language="C#" AutoEventWireup="false" CodeBehind="SalesRepAdmin.ascx.cs" Inherits="com.company.medpack.GeneralAdministrationPL.SalesRepAdmin" EnableViewState="false" %>
<%@ Register Assembly="SAP.Web, Version=1.2.0.0, Culture=neutral, PublicKeyToken=50436dca5c7f7d23" Namespace="SAP.Web.UI.Controls" TagPrefix="sap" %>
<%@ Register Assembly="com.company.medpack.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=568487c0f56d688c" Namespace="com.company.medpack.Shared.Controls" TagPrefix="cc1" %>
<link href="C:\Program Files\SAP\Portal Add-in for Visual Studio 2005\Controls\ur\ur_design.css"  type="text/css" rel="stylesheet"/>
<style type="text/css">
    body
    {
        width:100%;
    }
    table
    {
        padding:0px;
        border:0px;
        margin:0px;
        border-collapse:collapse;
    }    
    .urSTbvColHdrLvl1Std th
    {
        color: #02358e; font-weight: bold;
    }    
    .urSTbvColHdrLvl1Std th a:active
    {
        color: #02358e; font-weight: bold;
    }
    .urSTbvColHdrLvl1Std th a:visited
    {
        color: #02358e; font-weight: bold;
    }    
    .urSTbvColHdrLvl1Std th a:link
    {
        color: #02358e; font-weight: bold;
    }    
    table tbody tr td
    {
        background:transparent;
    }
    .editBox
    {
        border: solid 1px silver;
        height: 17px;
    }    
</style>






<body class="prtlBody">

    <asp:HiddenField ID="hidSortExpression" runat="server" />
    <asp:HiddenField ID="hidSortOrder" runat="server" />
    <table cellpadding="5px" cellspacing="0">
        <tr>
            <td class="urTxtH2" align="left" colspan="2">Sales Rep</td>        
        </tr>
        <tr>
            <td valign="top">
                <div id="filterDiv" class="urTbsWhl">
                    <table>
                        <tr>
                            <td colspan="2" class="company_txt_emph" align="center">
                                Search Sales Rep</td>
                        </tr>
                        <tr>
                            <td class="company_txt_std">
                                Sales Rep:&nbsp;</td>
                            <td>
                                <asp:TextBox ID="txtSalesRepFilter" runat="server" Text="" CssClass="urEdf2TxtEnbl" MaxLength="10" /></td>
                        </tr>
                        <tr>
                            <td class="company_txt_std">
                                Account Manager ID:&nbsp;</td>
                            <td>
                                <asp:DropDownList  Font-Names ="Lucida Console"  Font-Size="X-Small"  ID="ddlAccountManagerIDFilter" runat="server"  CssClass="company_dropdownlist" EnableViewState="true"  
                                DataValueField="AccountManagerID"  DataTextField="AccountManagerName"  AutoPostBack="False" Width="175px"  /></td>
                        </tr>
                        <tr>
                            <td class="company_txt_std">
                                PCID:&nbsp;</td>
                            <td>
                                <asp:DropDownList  Font-Names ="Lucida Console"  Font-Size="X-Small"  ID="ddlPCIDFilter" runat="server"  CssClass="company_dropdownlist"
                                 DataValueField="PCID"  DataTextField="FullName"   AutoPostBack="False" Width="175px"  /></td>
                        </tr>
                        <tr>
                            <td class="company_txt_std">
                                Quote Request Approval Bypass:&nbsp; 
                            </td>  
                             <td> 
                                <asp:DropDownList ID="ddlRequestApprovalFilter" CssClass="company_dropdownlist" runat="server" Height="50px"  >
                                    <asp:ListItem Text="All" ></asp:ListItem>
                                    <asp:ListItem Text="No" ></asp:ListItem> 
                                    <asp:ListItem Text="Yes" ></asp:ListItem> 
                                </asp:DropDownList>&nbsp;&nbsp;
                             </td>                      
                        </tr>
                        <tr>
                            <td colspan="2" align="right">
                                <asp:Button ID="btnSearch" runat="server" Text="Search" CssClass="urBtnStd" Height="22px" />
                            </td>
                        </tr>
                        <tr>
                            <td align="left" colspan="2">
                                <asp:ValidationSummary runat="server" ID="valSearchValidationSummary" ValidationGroup="Search"
                                    CssClass="company_txt_std urTxtCrit" DisplayMode="List" ForeColor="" />
                            </td>
                        </tr>
                    </table>
                                       
                  
                </div>
            </td>
            <td valign="top">
                <div id="insertDiv" class="urTbsWhl">
                    <table>
                        <colgroup>
                            <col width="100px" />
                            <col width="100px" />
                        </colgroup>
                        <tr>
                            <td colspan="2" class="company_txt_emph" align="center">
                                Insert Sales Rep</td>
                        </tr>
                        <tr>
                            <td class="company_txt_std">
                                Sales Rep:&nbsp;</td>
                            <td valign="middle">
                                <asp:TextBox ID="txtSalesRepInsert" runat="server" Text="" CssClass="urEdf2TxtEnbl" MaxLength="10" /></td>
                        </tr>
                        <tr>
                            <td class="company_txt_std">
                                Account Manager ID:&nbsp;</td>
                            <td valign="middle">
                                <asp:DropDownList  Font-Names ="Lucida Console"  Font-Size="X-Small"  ID="ddlAccountManagerIDInsert" runat="server"  CssClass="company_dropdownlist"
                                DataValueField="AccountManagerID"  DataTextField="AccountManagerName"  AutoPostBack="False" Width="175px"  /></td>
                        </tr>                        
                        <tr>
                            <td class="company_txt_std">
                                PCID:&nbsp;</td>
                            <td valign="middle">
                                <asp:DropDownList  Font-Names ="Lucida Console"  Font-Size="X-Small"  ID="ddlPCIDInsert" runat="server"  CssClass="company_dropdownlist"
                                DataValueField="PCID"  DataTextField="FullName"  AutoPostBack="False" Width="175px"  /></td>
                        </tr>
                         <tr>
                            <td class="company_txt_std">
                                Quote Request Approval Bypass:&nbsp; 
                            </td>  
                            <td>    
                                <asp:DropDownList ID="ddlRequestApprovalInsert" CssClass="company_dropdownlist" runat="server" Height="50px" >
                                    <asp:ListItem>No</asp:ListItem> 
                                    <asp:ListItem>Yes</asp:ListItem> 
                                </asp:DropDownList>&nbsp;&nbsp;
                             </td> 
                            
                        </tr>                           
                        <tr>
                            <td align="right" valign="top" colspan="2">
                                <asp:Button ID="btnInsert" runat="server" Text="Insert" CssClass="urBtnStd" Height="22px"
                                    ValidationGroup="Insert" /></td>
                        </tr>
                        <tr>
                            <td align="left" colspan="2">
                                <asp:ValidationSummary runat="server" ID="valInsertValidationSummary" ValidationGroup="Insert"
                                    CssClass="company_txt_std urTxtCrit" DisplayMode="List" ForeColor="" />
                            </td>
                        </tr>
                    </table>
                    <asp:RequiredFieldValidator ID="valSalesRepRequired" runat="server" EnableClientScript="false"
                        ControlToValidate="txtSalesRepInsert" Text="" ErrorMessage="Valid Sales Rep ID Is Required"
                        Display="None" ValidationGroup="Insert" />

                   
                    
                </div>
            </td>
        </tr>
    </table>
    <br />    
    <br />
    <div id="resultsDiv">
        <table>
            <tr><td align="left"><asp:Label ID="lblMessage" runat="server" CssClass="company_txt_std urTxtCrit" ForeColor="red" Font-Bold="true" /></td><td align="right"><asp:Button ID="btnSave" runat="server" CssClass="urBtnStd" Text="Save" Height="22px" ValidationGroup="Edit" /></td></tr>
            <tr><td colspan="2">
                <cc1:MedPackGridView runat="server" ID="gvwDetails" CssClass="company_grid" Height="300px">
                    <HeaderStyle CssClass="company_grid_header_row" />
                    <RowStyle CssClass="company_grid_row" />
                    <AlternatingRowStyle CssClass="company_grid_alt_row" />
                    <Columns>
                        <asp:TemplateField HeaderText="Sales Rep" SortExpression="SalesRepId" >                
                            <ItemStyle CssClass="company_grid_cell" Width="100px" />
                             <ItemTemplate>
                                <asp:Literal ID="litSalesRep" runat="server" Text='<%#Eval("SalesRepId")%>'/>
                            </ItemTemplate>                                    
                        </asp:TemplateField>       
                        <asp:TemplateField HeaderText="Account Manager ID" SortExpression="AccountManagerId" >                
                            <ItemStyle CssClass="company_grid_cell" Width="150px" />
                            <ItemTemplate>
                             <asp:DropDownList  Font-Names ="Lucida Console"  Font-Size="X-Small"  ID="ddlAccountManagerID" runat="server"  CssClass="company_dropdownlist"
                                DataValueField="AccountManagerID"  DataTextField="AccountManagerName"  AutoPostBack="False" Width="125px"   />
                             </ItemTemplate>                                    
                        </asp:TemplateField>                                                                         
                        <asp:TemplateField HeaderText="PCID" SortExpression="PCID" >
                            <ItemStyle CssClass="company_grid_cell" Width="100px" />
                            <ItemTemplate>
                            <asp:DropDownList  Font-Names ="Lucida Console"  Font-Size="X-Small"  ID="ddlPCID" runat="server"  CssClass="company_dropdownlist"
                                DataValueField="PCID"  DataTextField="FullName"  AutoPostBack="False" Width="80px" AppendDataBoundItems="true"   />
                            </ItemTemplate>                                    
                        </asp:TemplateField>
                        
                        <asp:TemplateField HeaderText="Quote Request Approval Bypass" SortExpression="BypassRequestApproval" >
                            <ItemStyle CssClass="company_grid_cell" Width="100px" />
                            <ItemTemplate>
                                <asp:DropDownList ID="ddlRequestApproval" CssClass="company_dropdownlist" runat="server" Height="60px" Width="75px" >
                                    <asp:ListItem value="0" text="No"/> 
                                    <asp:ListItem value="1" text="Yes"/>
                                 </asp:DropDownList>
                            </ItemTemplate>                                    
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Delete">
                            <ItemStyle CssClass="company_grid_cell" Width="50px" />
                            <ItemTemplate>
                                <asp:CheckBox ID="chkDelete" runat="server" Checked='<%#Eval("Deleted")%>'  />
                            </ItemTemplate>                
                        </asp:TemplateField>
                        
                                                                                                     
                    </Columns>
                </cc1:MedPackGridView >
            </td></tr>
        </table>
    </div>     

</body>

Open in new window

It looks ok. I can only think there is a issue with the data being bound to it, I have had problems in the past when I didnt use a primary key in the databind.

The next thing I would do is just focus on one of them, and hard code some listitem values and check you get the selected index in this case, if you do then you know it is an issue with the databinding.

Also I am not sure what the other components on the page are (custom controls) - it may be worth removing them while you debug, just to be sure they are not having some strange effect on the postback/viewstate etc.

Author

Commented:
I have found out the issue is EnableViewState on the page was not set to true. After setting this to true when I would post back the controls would hold the values. I have given you partial credit becuase I did follow your advice and moved things to the btn click event where it makes more sense. Thanks.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial