Selecting values in DDLs with values from SQL DB

On my page I have four drop-down lists: startWeek, startYear, endWeek and endYear which sets a period of time.The default values, that must be displayed on page load, are selected from a table called Period in a SQL database using a Linq.DataContext class called MyContextClass. The periods (a period is a week in a given year) in this table can be active/inactive. In the code I select two active periods: The one with the lowest ID (the earliest period) and the one with the highest ID (the latest period). I then try to display these two periods in the four drop downs: the first two lists contain the week and the year of the earliest period and the last two contain the week and the year of the latest period. I have two problems:

1. When the method below is called upon Page_Load, the method selects the end-values, that is, the end-week and the end-year, in both sets of drop-down lists! Fx. if the start period is week 32 in 2008 and the end period is week 12 in 2009, then "12" and "2009" is selected in both startWeek/startYear and endweek/endYear. However, if I call this method outside the PageLoad method, it works fine and displays the start- and end-periods correctly! what is wrong? I have debugged it, and it seems that the correct values are selected in the startweek/startYear drop-downs at first, but then overwritten later... I can't figure out why!

2. I choose the selected value in each drop down by looping through a IQueryable element although I know for sure, that it will only hold one element. How do I do this without the loop?


private void SetPeriods()
            MyContextClass db = new MyContextClass();

            var periods = from p in db.Periods
                          where p.Active
                          select new { p.ID, p.Name, p.Year };

            int startPeriodID = periods.Min(period => period.ID);
            int endPeriodID = periods.Max(period => period.ID);

            IQueryable startPeriodName = periods.Where(period => period.ID == startPeriodID).Select(period => period.Name);
            IQueryable endPeriodName = periods.Where(period => period.ID == endPeriodID).Select(period => period.Name);
            IQueryable startPeriodYear = periods.Where(period => period.ID == startPeriodID).Select(period => period.Year);
            IQueryable endPeriodYear = periods.Where(period => period.ID == endPeriodID).Select(period => period.Year);

            foreach (var p in startPeriodName)
                this.StartWeekDdl.SelectedValue = p.ToString();

            foreach (var p in startPeriodYear)
                this.StartYearDdl.SelectedValue = p.ToString();

            foreach (var p in endPeriodName)
                this.EndWeekDdl.SelectedValue = p.ToString();

            foreach (var p in endPeriodYear)
                this.EndYearDdl.SelectedValue = p.ToString();


10/27/2008 12:47:04 PM 93655 articles. 6 followers. Follow

2 Replies

Similar Articles

[PageSpeed] 51

Have you tried using the FindByValue or FindByText methods of the DropDown list along with the Single() method to select the value instead of the loops? something like.

StartWeekDdl.FindByValue(startPeriodName).Selected = true --if you are putting the PeriodName in the value of the dropdown


StartWeekDdl.FindByText(startPeriodName).Selected = true --if you are putting the PeriodName in the text of dropdown


And use the Single() method rather than getting the values back as an IQueryable interface, something like

string startPeriodName = periods.Where(period => period.ID == startPeriodID).Select(period => period.Name).Single();



10/27/2008 5:10:32 PM

Thanks for your response. The problem was infact, that I was using the same ListItem array to populate the StartWeekDdl and the EndWeekDdl and the same ListItem array to populate the StartYearDdl and the EndYearDdl. So, when the code updated the EndWeekDdl it updated the ListItem array of the StartWeekDdl too (as it was the same array), and thereby displayed the same item in both lists.

Anyway, the Single method was just was I was looking for. Thanks!

10/28/2008 8:27:43 AM

Similar Artilces:

problem in selecting value from dropdown inside a repeater and inserting the selected value inside db
there is  checkbox and drop down inside my  item template of repeater in one page.Based on that drop down and check box selection calculation will be done in another page which will be inserted inside a db.I cannnot fetch the value from the dropp down in my save page  and as a resut data cannot be inserted inside db. plz help!!  <asp:Repeater ID="rptmenproduct" runat="server" >                      <HeaderTemplate>    <...

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++)        {       &...

SQL db value or AppSettings value, performance?
i have this question on performance. now i'm loading on each page pre_init request a value out of my SQL db, would it be faster or more effecient to get this value out of my web.config where i could store this value in the AppSettings part? normally this value is changed 4 to max 6 times a year, but since i read this article how to change programmatically a value in the web.config i don't see any problem why i shouldn't store it in the web.config, besides the fact of performance off course. this site has atm about 70 to 90 visitors or 600 to 900 page views a day. by introducing the n...

Passing Values from a Web Form to Another Web Form
Hello All! I am trying to pass values from one web form to another web form. I know that there are 3 ways of doing this: queryString, Server.Transfer and Session. I am using the Server.Transfer method. But I am not able to create, in my 2nd web form, an instance of my 1st web form. My 1st Web form is named CallTrack.aspx and my 2nd is named Export.aspx. What I mean is something like this: Public value as CallTrack. I can't create it in my 2nd web form because when the intellisense is displayed, there's no CallTrack in the options. Thanks!   How about using cross-...

Default selecting listbox values based on DB values...
I have the following code in .aspx file:<asp:listbox selectionmode="Multiple" rows="6" cssclass="FormElement" datasourceid="Unions" id="ctlUnions" tabindex="25" runat="server" datatextfield="short_name" datavaluefield="union_id"></asp:listbox><asp:SqlDataSource id="Unions" datasourcemode="DataSet" enableviewstate="true"            enablecaching="true" cacheduration="Infinite" cacheexpirationpolicy="Absolute"            ConnectionString='<%$ ConnectionStrings:strDataSource %&g...

If Not value or value then....
Hi all,I want to write a simple IF Not then statement in 2.0 and I would like some help please.  If Not ntuser = "DOMAIN\ntuser" Or ntuser = "DOMAIN\ntuser2" Then Panel1.Visible = False End If Doesnt work, can you tell me where i'm going wrong please?many thanks.  The first place you're going wrong is in telling us it "doesn't work" without providing any details. JeffPlease: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue. Use Not as stated below. It ...

find values in sql server and display different values on web page
my challenge:if the user is not found in tbl then display nothingif the user is found in the tbl and has a level value of 1 then display the following: cn, u, a, cif the user is found in the tbl and has a level value of 2 then display the following: cn, u, a, c, adNavigationView(MyUserID);if (NavigationView(MyUserID) == true) {  Label1.Text = "true"; }protected bool NavigationView(String MyUserID){  String strConnection;  strConnection = ConfigurationManager.ConnectionStrings["MyConnection"].ToString();  SqlConnection objConnection = new SqlConnection(strConnect...

passing values to .net web form application
Hi Can any explain me abt how to pass values to my .NET web form application (designed using PB 11.1) from other web application? My intension is to redirect from a web application (ASP.NET to .net web form application) to my web application with user information. Thanks & Regards, Anbazhagan From the "Deploying Applications and Components to .NET" manual: >>> Starting an application with command line parameters If your application requires command line parameters, you can assign values to the PBCommandParm global property before you deploy the...

get value from <select> value & display value
hi all, i want these two bold values which are below,  underline value i can get but second bold value i m not avail to get please help.... <select><option value="ma">manoj</option> </select> regard khushak  P.S. if possible then Please with  java script other wise code behind New In .NET World See my post in this thread.  That should take care of you. Peter BrunoneMS MVP, ASP.NETFounder, EasyListBox.comDo the impossible, and go home early....

How to insert dropdownlist selected value into sql DB table
  Normal 0 false false false MicrosoftInternetExplorer4 /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; ...

Update selected RadioButtonList value to a label in a web form
 I have a web form and when you click a button, a ModalPopUp-control opens. It contains a RadioButtonList. All I want is that when user selects one of the RadioButtons in ModalPopup, it's value is updated back to a web form (label-control) using codebehind.  When I click the Update-button on the ModalPopup, the correct value (RadioButtonList's SelectedItem.Text) is passed and set to label's text-property, but label remains empty on the web form so it won't update.  Anyone, please? Hi k000der, From your description, I understand that you use the ModalPopupE...

select cheboxlist if any values are selected in sql
hello and thanks in advance,  I have a checkboxlist that is created dynamically from table1 once the records are inserted they are inserted in table2. i can save the values into the table and remove them if i uncheckd them that is working fine. the problem is to checked the items that have been selected already, how to i do this?? really really confuse...   here is the cs code; namespace IMS_2K9.Admin { public partial class Order_Charges : System.Web.UI.Page {private string connectionString = WebConfigurationManager.ConnectionStrings["IMSCon...

SQL QUERY replace NULL value in a row with a value from the previous known value
Hi!! I have a table with no unique ID, I created an Id with ROW_NUMBER () OVER (ORDER BY column asc) rank and created a stored procedure with the rank and table. In this stored procedure I want to create an extra column that checks if the value from another columns contains value = 100 rank,Ifnummer,followingnr,productnr testing 2313,'6497269','001' ,412 , NULL 2314,'6497269','002' ,413 , NULL 2315,'6497269','003' ,100 , yes 2316,'6497269','004' ,430 ,NULL ...

Cascading Dropdown - Initially selected value
Hi there, I am having an issue with a pretty basic problem. I have managed to get the cascading drop down lists working ok with information coming from a database. On the initial page, I need to have a value in the drop down list already selected, i.e. the current year in one drop down and current month in the next. The information from both of these is sent to a query to output a datatable. Can anyone help with this? I'm not sure I understand the scenario, but I think the new CascadingDropDownNameValue(..., defaultValue) constructor may be just what you're looking for. (First available ...

Web resources about - Selecting values in DDLs with values from SQL DB -

Consultation Document on the Methods for Selecting the Chief Executive and for Forming the LegCo in 2012 ...
The " Consultation Document on the Methods for Selecting the Chief Executive and for Forming the LegCo in 2012 " was a document published on ...

Voting Machine Caught on Camera Casting Ballot for Democrat when Selecting Republican - YouTube
**UPDATE.... I've heard many reports that this is "just a calibration issue." I will say this... when I went to page 2 and began voting for city ...

Selecting The Right Jeans
Fit, style, cut, colour and wash all factor into the pursuit for great denim.

Clock ticking on selecting successor to Leigh Clifford at Qantas
With Qantas on course to chalk up its largest annual profit since 2008, the question now is whether chairman Leigh Clifford is looking to hang ...

Why are the reserves selecting the team?
Backbenchers are the reserves of the parliamentary system. They are newcomers.

Jackie French: Why selecting the right place for your plants is important
The secret of growing anything easily is to choose the best spot for what you want to grow.

Netflix turns to pirates when selecting new shows
Imagine the surprise, then, when the popular video streaming site admitted that it actually turns to torrenters for inspiration. "With the purchase ...

Boston Marathon bombing trial: Judge, lawyers face challenges in selecting jurors - CTV News
As the second phase of jury selection began in the federal death penalty trial of Boston Marathon bombing suspect Dzhokhar Tsarnaev, it immediately ...

Selecting cabinet one of first orders of business for Trudeau
One of the first orders of business for any new prime minister is picking a cabinet. Who is likely to make the cut?

Agile Analysis, Self-Selecting Teams, TDD & BDD in Methods & Tools Winter 2014 issue
... for software developers, testers and project managers – has just published its Winter 2014 issue that discusses Agile Analysis, Self-Selecting ...

Resources last updated: 12/22/2015 12:43:02 AM