Dynamic dropdownlist is always returning the first value, not the selected value!

Hello guys,

 this is my first time posting a question. I am very very frustrated and depressed because of my project, i hope someone can help.

 

I created two dropdownlists. When you select an item on the first (static) dropdownlist, the second dropdownlist will connect to the database and retrieve records according to the selected item on the first. When you select an item on the second (dynamic) dropdownlist, it's supposed to return the selected value. But for some reason, it's always returning the first value and not the selected one.

Here's the simple yet frustrating code.

 string constring = ConfigurationManager.ConnectionStrings["PLR_test"].ConnectionString;

 

protected void Page_Load(object sender, EventArgs e)

{

SqlConnection con = new SqlConnection(constring);

//ddSubject is the first (static) dropdownlistSqlCommand cmd = new SqlCommand("SELECT Category, CallNumber, Title, Author from Book WHERE CATEGORY = '" + ddSubject.SelectedItem.Value.ToString() + "'", con);

con.Open();

SqlDataReader read = cmd.ExecuteReader(CommandBehavior.CloseConnection);

//ddBook is the second (dynamic) dropdownlist 

ddBook.Items.Clear();

while (read.Read())

{

ListItem li = new ListItem();

li.Text = read["Title"].ToString() + " / " + read["Author"].ToString();

li.Value = read["CallNumber"].ToString();

ddBook.Items.Add(li);

}

con.Close();

}

protected void btnReserve_Click(object sender, EventArgs e)

{

 

SqlConnection con1 = new SqlConnection(constring);

SqlCommand cmd1 = new SqlCommand("ReserveBook", con1);

cmd1.CommandType = CommandType.StoredProcedure;

cmd1.Parameters.Add("@CategoryCode", SqlDbType.NChar, 3);

cmd1.Parameters["@CategoryCode"].Value = ddSubject.SelectedItem.Value.ToString();

cmd1.Parameters.Add("@CallNumber", SqlDbType.NChar, 3);

//This part is the error. It's always returning the first value, instead of the selected valuecmd1.Parameters["@CallNumber"].Value = ddBook.SelectedValue.ToString();

 

cmd1.Parameters.Add("@MLSUserID", SqlDbType.NVarChar, 50);

cmd1.Parameters["@MLSUserID"].Value = "ILUZADAE";

con1.Open();

cmd1.ExecuteNonQuery();

con1.Close();

Response.Redirect(
"Reserved.aspx");

 

}

Please help, programming masters. Thank you very much in advance!! Big Smile

0
callbooks
8/22/2008 1:04:10 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

14 Replies
2564 Views

Similar Articles

[PageSpeed] 26

by reloading the second dropdownlist on every postback, you are wiping out the users selection.

you should only reload it when the first ddl changes


Mike Banavige
~~~~~~~~~~~~
Need a site code sample in a different language? Try converting it with: http://converter.telerik.com/
0
mbanavige
8/22/2008 2:06:34 AM

Try place code binding data on dropdown 2 in dropdown1's "SelectedIndexChanged Event".


Please mark the post(s) that have helped you as "Answer"
0
thuhue
8/22/2008 2:10:48 AM

I agree with Mike! When populating your DropDownList in Page_load event, then be sure to wrap your codes for binding with NOT IsPostback block so that the DropDwonList state will not refresh on postbacks...

protected void Page_Load(object sender, EventArgs e)
{

   if (!Page.IsPostBack){
    // Populate your DDL here
   }

}


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
8/22/2008 2:11:16 AM
Thank you very much. I never thought it was that simple. Your answer solved my problem. A gaziillion thanks!! Big Smile
0
callbooks
8/22/2008 3:00:48 AM

 hello,

i am having this same exact problem, but moving my databind for the ddl to the page_load inside if(!Page.IsPostBack) has not fixed the problem!  i'm at my wits end!!  i have a ddl that is bound in page_load with a list of reports.  a button has a click event handler that then looks for the selected value of the ddl to open the selected report.  no matter where/when i bind my ddl, the selected value is ALWAYS the first item in the ddl.  can anyone help me???  :-( 

aspx page:

1    <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="ReportViewerForm.aspx.cs" Inherits="ReportViewerForm" Title="SABC Staffing Schedule" %>
2    
3    <%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
4        Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
5    
6    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
7    
8        <table width="100%">
9            <tr>
10               <td> </td>
11           </tr>
12           <tr class="displayFont">
13               <td>  
14                   <asp:DropDownList ID="ddlRptName" runat="server" Width="323px"/>
15                     
16                   <asp:Button ID="btnViewReport" runat="server" OnClick="btnViewReport_Click" Text="View Report" />
17               </td>
18           </tr>
19           <tr>
20               <td> </td>
21           </tr>
22           <tr>
23               <td>
24                   <rsweb:reportviewer id="rptVwr" runat="server" height="592px" width="100%"/>
25               </td>
26           </tr>
27       </table>
28   
29       <asp:ObjectDataSource ID="ReportsDataSource" runat="server" DeleteMethod="Delete" InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" SelectMethod="GetReports" TypeName="ReportsDataSetTableAdapters.tmdReportTableAdapter" UpdateMethod="Update">
30           <DeleteParameters>
31               <asp:Parameter Name="Original_ReportID" Type="Int32" />
32           </DeleteParameters>
33           <UpdateParameters>
34               <asp:Parameter Name="Name" Type="String" />
35               <asp:Parameter Name="Path" Type="String" />
36               <asp:Parameter Name="Description" Type="String" />
37               <asp:Parameter Name="Original_ReportID" Type="Int32" />
38           </UpdateParameters>
39           <InsertParameters>
40               <asp:Parameter Name="Name" Type="String" />
41               <asp:Parameter Name="Path" Type="String" />
42               <asp:Parameter Name="Description" Type="String" />
43           </InsertParameters>
44       </asp:ObjectDataSource>
45   
46   </asp:Content>
47   
48   

code behind:

1    using System;
2    using System.Data;
3    using System.Configuration;
4    using System.Collections;
5    using System.Web;
6    using System.Web.Security;
7    using System.Web.UI;
8    using System.Web.UI.WebControls;
9    using System.Web.UI.WebControls.WebParts;
10   using System.Web.UI.HtmlControls;
11   using Microsoft.Reporting.WebForms;
12   using System.Security.Principal;
13  
14   public partial class ReportViewerForm : System.Web.UI.Page
15   {
16       private string reportServer;
17       private string reportPath;
18  
19       protected void Page_Load(object sender, EventArgs e)
20       {
21           reportServer = ConfigurationManager.AppSettings["ReportServer"].ToString();
22           reportPath = ConfigurationManager.AppSettings["ReportPath"].ToString();
23  
24           this.Page.EnableViewState = false;
25           this.rptVwr.Visible = false;
26  
27           if (!Page.IsPostBack)
28           {
29               ((DropDownList)ddlRptName).AppendDataBoundItems = true;
30               ListItem emptyReportSelection = new ListItem("Select a report", "");
31               ((DropDownList)ddlRptName).Items.Add(emptyReportSelection);
32               ((DropDownList)ddlRptName).DataSource = ReportsDataSource;
33               ((DropDownList)ddlRptName).DataTextField = "Name";
34               ((DropDownList)ddlRptName).DataValueField = "Path";
35               ((DropDownList)ddlRptName).DataBind();
36           }
37       }
38  
39       protected void btnViewReport_Click(object sender, EventArgs e)
40       {
41           //get path for selected report
42           string selectedReport = ((DropDownList)ddlRptName).SelectedValue;
43           if (!selectedReport.Equals(""))
44           {
45               string fullReportPath = reportPath + selectedReport;
46  
47               //setup network credentials
48               System.Net.NetworkCredential nc =
49                           new System.Net.NetworkCredential(ConfigurationManager.AppSettings["ReportUser"],
50                                                            ConfigurationManager.AppSettings["ReportPassword"],
51                                                            ConfigurationManager.AppSettings["ReportDomain"]);
52  
53               System.Net.CredentialCache cc = new System.Net.CredentialCache();
54               try
55               {
56                   this.Page.EnableViewState = true;
57  
58                   this.rptVwr.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
59                   this.rptVwr.ServerReport.ReportServerUrl = new Uri(reportServer);
60                   this.rptVwr.ServerReport.ReportPath = fullReportPath;
61  
62                   cc.Add(this.rptVwr.ServerReport.ReportServerUrl, "Negotiate", nc);
63                   this.rptVwr.Visible = true;
64               }
65               catch (Exception ex)
66               {
67                   throw ex;
68               }
69               finally
70               {
71                   nc = null;
72                   cc = null;
73               }
74           }
75       }
76   }
77  

 
0
chinacat456
8/27/2008 12:07:13 AM

Have you tried thuhue's solution? (Check his post above)

 His extremely simple suggestion resolved my problem. :)

0
callbooks
8/27/2008 12:21:17 AM

i only have 1 dropdownlist....so i'm not sure how that solution will help me.  thanks though!

0
chinacat456
8/27/2008 12:57:40 AM

try not disabling viewstate.


Mike Banavige
~~~~~~~~~~~~
Need a site code sample in a different language? Try converting it with: http://converter.telerik.com/
0
mbanavige
8/27/2008 1:05:48 AM

I'm also a newbie, but please try this one. 

 Declare "string selectedReport" publicly. (outside the events)

 Then, put this code on the event ddlRptName_SelectedIndexChanged

 string selectedReport = ((DropDownList)ddlRptName).SelectedValue;

See if it will return the selected value if you click the button.

 

 


0
callbooks
8/27/2008 1:06:40 AM

not disabling viewstate fixed the problem!!  thanks!!!!!

0
chinacat456
8/27/2008 1:15:55 AM

Hi chinacat456,

Try to Remove Line 24 in your codes..

24           this.Page.EnableViewState = false;


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
8/27/2008 1:23:10 AM

Hello guys! I tried the solution on ASP.NET 1.1. I did not edit the code at all. But it's not working! It does not populate the second dropdownlist. I already pasted the code on the first dropdownlist's selectedindexchanged, but it still won't work. I wonder why.. Could this be a bug on ASP.NET 1.1?

 (By the way, The firstdropdownlist is on AutoPostBack, so that it would reload the page and eventually populate the second dropdown. This was working on ASP.NET 3.5. But not in 1.1)

 

 

0
callbooks
9/4/2008 3:17:23 AM
Oh, I see the problem now. The click events, and selectedindex changed events are not firing! What could have caused this?
0
callbooks
9/4/2008 3:26:23 AM

in asp.net 1.1, the controls in your markup also need to be declared in your codebehind using the withevents keyword.


Mike Banavige
~~~~~~~~~~~~
Need a site code sample in a different language? Try converting it with: http://converter.telerik.com/
0
mbanavige
9/4/2008 9:30:12 AM
Reply:

Similar Artilces:

Dropdownlist selected value passes first value in list no matter what value is selected. why ?
 HI . I have a dropdownlist. Databinds ok but when I must pass a value as a Selected value it always passes the first value in the list even if I select another value. I tried to set the ddl to enableviewstate false but it doesn't change anything. Any ideas ? Code below, thanksLoading the ddl:       productCategories = CatalogAdmin.Admin_Product_Categories_NotIn(productId);        for (int i = 0; i < productCategories.Rows.Count; i++)        {       &...

SelectedItem.Value always returns the same value in DropDownList
Hi, I have a DDL inside a DataGrid and I added values into it using <asp:ListItem>1</asp:ListItem>. Even upon selection of different values, it always returns the same value. What additional feature, do I need to manage here?? Thanks,Shravan Addaypally MCP Can you post your HTML code for the dropdown? My guess based on the posted tag is, you are not setting value for each item. Like adanti says....maybe you haven't set a value for each item......I think it's better if you use this..... <asp:ListItem Text="text1" Value="value1"/> and so on ...

DropDownList always selecting first value!!
I have a drop down list that properly gets it's values from an Oracle table, but seems to be stuck on the first item in the list. When you select any other item in the list, it seems to think that the first item in the list is selected. When I check the html source from the page all of the tags seem correct. Is there something I am missing.....Here is my data binding code. dim strConn as String = {My Connection String} dim objCon as oledbconnection = New oledbconnection(strConn) dim strSQL as String = "Select GROUP_NAME FROM GROUPS" dim cmd as oledbcommand = new oled...

How Select one dropdownlist value using down arrows corresponding other dropdownlist value are select
I am using two dropdownlist box.One is used for country selection. other one is used for state selection.I am using dropdown selectedindexchanged event. when i click country dropdownlist corresponding state is selected in state dropdownlist box. How select the country in country dropdownlist using down arrow keys at the same time corresponding state is select in state dropdown list.R.Karthikeyan   kartmca: How select the country in country dropdownlist using down arrow keys at the same time corresponding state is select in state dropdown list.Generally, we don't implmenet...

Databound dropdownlist always selecting first value
Hi,  I've created a databound dropdownlist from an Access database which then throws the values into a Querystring, however, no matter what selection you make, it always uses the first value in the list. Can anybody help? Here is my code, it's VB.NET:     Dim MyDBConn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=DataBase.mdb;")    Dim MyDBAdap As New OleDbDataAdapter    Dim MyDS As New DataSet    Dim MyDBCmd As New OleDbCommand    Dim MyDR As OleDbDataReader Prote...

DropDownList selected value determines value of second DropDownList
I have a quick question that I'm sure has been addressed before, but I can't seem to find a solution. I have two drop down list fields: startTime and endTime coded as such: <asp:DropDownList id="startTime" runat="server"> <asp:ListItem Value="00:00">12:00 A.M.</asp:ListItem> <asp:ListItem Value="00:30">12:30 A.M.</asp:ListItem> <asp:ListItem Value="01:00">1:00 A.M.</asp:ListItem> <asp:ListItem Value="...

Return Selected Value from Dynamic DropDrownList Custom Control
I have created a custom server control to dynamically populate the number of dropdownlist required by the web application. I am using *.ascx wif codebehind. The population of dropdownlists is done within a placeholder control. But i am unable to capture the values selected by the user from the dynamic dropdownlists. Is there anyway to do it? Pls let mi know. Thanx u...Whoever undertakes to set himself up as a judge in the field of truth and knowledge is shipwrecked by the laughter of gods. Yes, there is. Add the DDL's before the Init event: protected override void OnInit(Eve...

when loading a previously created record on to form, some controls are missing values(controls are depended on values selected in other controls)
Hello - I have created a page for Editing records.  this page will open up a chosen record and allow user to edit the data.On the form, I have 3 drop down lists.   The second dropdown list should fill values depending on value chosen in first dropdown list.  The third dropdown list should show/fill values depending on value chosen in second dropdown list.So taking this into count, i have several records with various data.  When I open-up/load a record in Edit form, only the first dropdown list has a value selected that was the pre-existing va...

On selecting value in second listbox. selected value in first textbox is lost
     Hello all, In a webapplication , I have to store the selected values in hidden fields with following code  <INPUT type="hidden" name="hidPatient" value=""> <INPUT type="hidden" name="hidPatientStatus" value="">  when i select the value in any list box following javascript function is called with this code   Response.Write "<SELECT id=" & strSelName & " name=" & strSelName & " validation=" & strValidation & " ...

dropdownlist's selected index value is not printing the selected value
Here iS my code .Aspx Page <asp:DropDownList ID="ddlkeyword" runat="server" Width="204px" DataTextField="Form" DataValueField="Form" OnSelectedIndexChanged="ddlkeyword_SelectedIndexChanged" >   </asp:DropDownList> <asp:Button ID="Button1" runat="server" Text="Submit" Width="110px" OnClick="Button1_Click" /> my aspx.cs protected void Page_Load(object sender, EventArgs e) { fillddlkeyword(); }protected void Page_Init(object sender, EventArgs e) { ...

superreview cancelled: [Bug 270342] In <threadPane.js>, "Warning: function MsgSortThreadPane does not always return a value" and "Warning: function MsgToggleThreaded does not always return a value" :
neil@parkwaycc.co.uk <neil.parkwaycc.co.uk@myrealbox.com> has cancelled Serge GAUTHERIE <gautheri@noos.fr>'s request for superreview: Bug 270342: In <threadPane.js>, "Warning: function MsgSortThreadPane does not always return a value" and "Warning: function MsgToggleThreaded does not always return a value" https://bugzilla.mozilla.org/show_bug.cgi?id=270342 Attachment 166201: (Av1) <threadPane.js> https://bugzilla.mozilla.org/attachment.cgi?id=166201&action=edit ------- Additional Comments from neil@parkwaycc.co.uk <neil.parkw...

superreview granted: [Bug 270342] In <threadPane.js>, "Warning: function MsgSortThreadPane does not always return a value" and "Warning: function MsgToggleThreaded does not always return a value" : [
David Bienvenu <bienvenu@nventure.com> has granted Serge GAUTHERIE <gautheri@noos.fr>'s request for superreview: Bug 270342: In <threadPane.js>, "Warning: function MsgSortThreadPane does not always return a value" and "Warning: function MsgToggleThreaded does not always return a value" https://bugzilla.mozilla.org/show_bug.cgi?id=270342 Attachment 168078: (Av2b) <threadPane.js> https://bugzilla.mozilla.org/attachment.cgi?id=168078&action=edit ...

superreview requested: [Bug 270342] In <threadPane.js>, "Warning: function MsgSortThreadPane does not always return a value" and "Warning: function MsgToggleThreaded does not always return a value" : #3
Serge GAUTHERIE <gautheri@noos.fr> has asked David Bienvenu <bienvenu@nventure.com> for superreview: Bug 270342: In <threadPane.js>, "Warning: function MsgSortThreadPane does not always return a value" and "Warning: function MsgToggleThreaded does not always return a value" https://bugzilla.mozilla.org/show_bug.cgi?id=270342 Attachment 168078: (Av2b) <threadPane.js> https://bugzilla.mozilla.org/attachment.cgi?id=168078&action=edit ...

superreview requested: [Bug 270342] In <threadPane.js>, "Warning: function MsgSortThreadPane does not always return a value" and "Warning: function MsgToggleThreaded does not always return a value" : #2
Serge GAUTHERIE <gautheri@noos.fr> has asked David Bienvenu <bienvenu@nventure.com> for superreview: Bug 270342: In <threadPane.js>, "Warning: function MsgSortThreadPane does not always return a value" and "Warning: function MsgToggleThreaded does not always return a value" https://bugzilla.mozilla.org/show_bug.cgi?id=270342 Attachment 166201: (Av1) <threadPane.js> https://bugzilla.mozilla.org/attachment.cgi?id=166201&action=edit ...

Web resources about - Dynamic dropdownlist is always returning the first value, not the selected value! - asp.net.presentation-controls

Tag Synonyms - Stack Overflow
Q&A for professional and enthusiast programmers

Accidental entities - what about the UI?
This post is a follow-up to my previous blog post " Accidental entities - you don't need that identity ". In that post, we followed a consultant ...

Flash Builder Plug-in for SAP Netweaver Gateway - Adobe Labs
Search Navigation Labs Home Wiki Home Technologies Alchemy Blueprint Camera Profiles and DNG Profile Editor Cirrus ColdFusion 10 DNG Codec Fireworks ...

Air Astana - Join Now
Thank you for considering membership of Nomad Club – Kazakhstan’s first Frequent Flyer Program. You could soon be on your way to earning free ...

Languages -> C# Articles, Tutorials, Examples: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Blog - Avisra
Avisra Web Development Home Blog Services Contact The Blog Latest Module Builder: How can we make it better? Sitefinity by Chris on July 2, 2013 ...

Online Booking Tool Support
This Online Booking Tool Support page might help you as you navigate through the process of booking travel through your OBT provided by CWT. ...

@Html and beyond
... ); } return string .Format( “{0}{1}” , me.Member.Name, id); } The Html building methods are quite simple. Building a dropdownlist for a ...

Top Ranked Articles
Top Ranked Articles - Free source code and tutorials for Software developers and Architects.; Updated: 23 Feb 2013

Unit Testing DateTime.Now Without Isolation
public virtual void SeedWithYearsSince(DropDownList list, int year){ for (int index = year; index

Resources last updated: 1/19/2016 12:39:48 AM