Can a DataSource set the default value in a DropDownList (or the list fetch the value from a DataSource)?

Hi

I have a DropDownList that gets its values from a DataSource-control. Nothing magic so far. What makes me scratch my head is that I need to set the default (selected) value in the drop down.

As the values come from a data source, I do not know the key/value/index of the default I. Is there a possibility to make the drop down "ask the data source" which key should be the default (that is, only if the drop down is populated the first time, of course)?

Background: I have an application where an administrator can set the "standard" month that the application should use. This value needs to be configurable by the admin. Now I could save the value to a database. And then? How to get it into my "Month"-drop down?

As I have *lots* of drop downs like this and as I tend to forget things I have to do over and over again, I would rather not use the drop downs "OnDataBound" or something similar to set the default value. I would rather fancy something similar to the paging-support of a GridView: it asks the data source, how many rows there are in total and uses this to calculate the number of pages needed.

 

Kind regards

guybrush

0
guybrush
1/14/2009 1:37:38 PM
asp.net.web-forms 93655 articles. 5 followers. Follow

9 Replies
1271 Views

Similar Articles

[PageSpeed] 19

 I do not think you have this on a platter.. The DataSource is just a data source, it does not know which control uses this data.. So, you need to have some code to set this.. If  that standard month is a "Key" of the Item that you get from that database, may be you can assign some fixed value for this, like "MAGICKEY", while you are saving this into the database and then set that Key as the default item for the drop down.. Sorry to disappoint you, but I do not think there is a magical way to do this.. If there is, I would like to know as well

 


Kumar Reddi
0
Kumar
1/14/2009 2:27:30 PM

My suggestion would to be query the database and retreive the "standard" month that the admin set "in your page load if not post back" and set your dropdownlist selected value = your retieved standard month.

I dont think there is a way for your datasource to let the dropdownlist know which value to select by default. I might me wrong though...


Sri
Please mark as answer if it helped you
0
jsriharsha
1/14/2009 2:29:33 PM

Have you considered creating your own User Control with the DropDownList where you would set SelectedValue?

0
kipo
1/14/2009 2:41:47 PM

Hi everyone 

Have you considered creating your own User Control with the DropDownList where you would set SelectedValue?

Yes, I thought about that. And I am not sure what I like better (or worse): use "OnDataBinding" or creating a custom user control. But it looks as I will have to decide, I think Tongue Tied

I'll leave the question open for a while, maybe someone still has an idea. But in the meantime: thank you all for your answers!

 

Regards

guybrush

0
guybrush
1/14/2009 2:58:31 PM

jsriharsha:

My suggestion would to be query the database and retreive the "standard" month that the admin set "in your page load if not post back" and set your dropdownlist selected value = your retieved standard month.

Hi,

Jsriharsha's solution is helpful, but how to retrieve the "standard" month that the administrator sets in the database. This means we need to know the standard value in advance. However,  it seems not practical.

Therefore, I suggest using the following method to fulfill the task:

1. Store all values the administrator sets in a XML file.

2. Set the DropDownList's AppendDataBoundItems property to true.

3. In the page load event, read the XML file and retrieve the default value.

4. Add the value to the DropDownList control.

The below demonstrates how to do this. Please take a look:

<%@ Page Language="C#" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    
    protected void Page_Load(object sender, EventArgs e)
    {
        //Read the XML file and get the default value of the DropDownList.
        //Add the value to the DropDownList control.
          DropDownList1.Items.Add(new ListItem("default value"));
       
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
       //Display the default value.
        Response.Write(DropDownList1.SelectedValue);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">


<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
          
        <asp:DropDownList ID="DropDownList1" runat="server" 
            DataSourceID="SqlDataSource1" DataTextField="name" DataValueField="name" AppendDataBoundItems="true">
        </asp:DropDownList>
      
     
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
            SelectCommand="SELECT [name] FROM [Photo]"></asp:SqlDataSource>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
     
    </div>
    </form>
</body>
</html>

Forward Sun
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Forward
1/19/2009 3:10:55 AM

Hi  Forward Sun - MSFT

Forward Sun - MSFT:

Therefore, I suggest using the following method to fulfill the task:

1. Store all values the administrator sets in a XML file.

2. Set the DropDownList's AppendDataBoundItems property to true.

3. In the page load event, read the XML file and retrieve the default value.

4. Add the value to the DropDownList control.

 

If I understand this correctly, this solution relies on the fact that the first entry in a DropDownList is selected by default if no value is explicitly selected. Correct?

This poses a problem in my situation: I'm talking about dates (or months). Now, months have an order. I cannot for example put June first in the list just because it is the default. My users would not appreciate June - January - February - March - ... in June, July - January - February - ... in July and so forth.

If this would not be the case, using "AppendDataBoundItems" would be a solution to consider. 

 

Kind regards

guybrush

0
guybrush
1/19/2009 7:44:47 AM

 You can update the PageLoad method and update the selected index of the drop down.


Bind GridView to Dynamically created DataTable | Bind DataTable to DropDownList

My Blog
0
shahed
1/19/2009 8:08:29 AM

guybrush:

If I understand this correctly, this solution relies on the fact that the first entry in a DropDownList is selected by default if no value is explicitly selected. Correct?

Yes, you are correct. Thanks for your feedback.

To avoid the issue, you can do as follows:

1. Store all values the administrator sets in a XML file.

2. Set the DropDownList's AppendDataBoundItems property to true.

3. In the page load event, read the XML file and retrieve the default value.

4. Add the value to the DropDownList control. Instead, add a string "Please select a value:" to the DropDownList control. Thus, if user missed to choose an item of the DropDownList control, its SelectedIndex value will be "0". In this case, set the a variable to the default value from the XML file . In other case, set the variable to the SelectedValue property of the DropDownList control.

<%@ Page Language="C#" %>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           DropDownList1.Items.Add(new ListItem("Please select a value:"));
        }
       
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string defaultValue =string.Empty;
        if (DropDownList1.SelectedIndex == 1)
        {
            defaultValue = "Default value";
        }
        else
        {
            defaultValue = DropDownList1.SelectedValue;
        }
        //Save the defaultValue to the database.
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">


<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
          
        <asp:DropDownList ID="DropDownList1" runat="server" 
            DataSourceID="SqlDataSource1" DataTextField="name" DataValueField="name" AppendDataBoundItems="true">
        </asp:DropDownList>
      
     
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
            SelectCommand="SELECT [name] FROM [Photo]"></asp:SqlDataSource>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
     
    </div>
    </form>
</body>
</html>

Forward Sun
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Forward
1/19/2009 9:53:10 AM

Hi Forward Sun - MSFT

Forward Sun - MSFT:
Thus, if user missed to choose an item of the DropDownList control, its SelectedIndex value will be "0". In this case, set the a variable to the default value from the XML file . In other case, set the variable to the SelectedValue property of the DropDownList control.

Yes, but this still boils down to something I have to do for each and every DropDownList I want to use this way. Don't get me wrong, I appreciate your input. It's just that I am very bad at things I have to do over and over again.

shahed.kazi:
You can update the PageLoad method and update the selected index of the drop down.

I assume you mean to attach to PageLoad or override OnLoad of the page. This as well comes down to something I have to do for every DropDownList.

So it seems, that I am (still) stuck with the decision if I rather implement the same thing for each DropDownList or if I create a custom "DefaultableDropDownList" or something. I will "resolve" this thread and thank you for all your valuable inputs.

 

Cheers

guybrush

0
guybrush
1/20/2009 1:27:07 PM
Reply:

Similar Artilces:

Drop down list in Form view returns error when value in bound field (data binding
I get the following error when I click edit to edit the details in the web form:'ddlUserRestrictionType' has a SelectedValue which is invalid because it does not exist in the list of items.Parameter name: value  I would like it to accept any value which currently exists in the database. Is this easily achievable? With what you've posted, all I can tell is that you are trying to set the SelectedValue of a ddl to a value that does not exist in the list.  It would be helpful if you can post some code and the expected values of this control.~ Timwww.bucketo...

DropDown List DataSource for Options *AND* for DataSource Value in Database?
  I have a DropDown object list and so far I can set it to EITHER: 1) A SINGLE value (From table A using DataSource1)2) Multiple value options (From table B using DataSource2)  But how do I set both of the above? (i.e. set it to the value of option DataSource1 but allow the user to set it to any value in DataSource2)  Thanks ! wht do u mean?? binding dropdown to one datasource containg ds1 and ds2??Please remember to "Mark As Answer" if this post answered your question!Bilal Shouman - MCAD.NET|My Blog|--------------------------------- you can only bind...

cascading dropdown set it's value only once but not on subsequent postbacks,web service recieve the value but can't set in dropdown
i have a dropdown named uxcommunity which is a dropdown and contain text in format ##-####-#### . and 2 more dropdowns province and district where province filters district. i get the first 2 characters ##  for session("province") and #### for session("District") and i have button to do the postback. first when the form loads and i click the button it get the value and select appropraite items in to dropdown province and district. but when i change the province dropdown content and district dropdown content and click the button , session will take correct...

DropDownList Question on setting the default value from the list
I fill my dropdownlist from a query, say 10 items the user has do some other things I wan to set the selected value to say "ABB" in my drop down list how can I do this Hi Iconley,  You could tie the DataBound event to an event handler, say:protected void dropList_DataBound(object sender, EventArgs e) { dropList.SelectedValue = "ABB"; }  That would make the active item in the dropdownlist the one with the value "ABB"  You could, of course, tie it to another event. Pete  OR.... you can do this,, really depends on your design.&l...

Is there any possible way that forms authentication can work on a web farm w/o each servers machine key values being set to the same thing?i have a site that is on a web farm and the servers dont have
 Is there any possible way that forms authentication can work on a web farm w/o each servers machine key values being set to the same thing?i have a site that is on a web farm and the servers dont have the machine keys set......but the forms authentication works fine. "Only when we are no longer afraid do we begin to live" -D. Thompson // f bush. ----------- "No man succeeds without a good woman behind him. Wife or mother, if it is both, he is twice blessed indeed." -Harold MacMillan A couple of things spring to mind. 1. Some form of "st...

Setting Style of Items in a dropdownlist based on dataSource Values?
Hi All,I am trying to set the style (Colour) of items in a dropdownlist based on a value held in the datasource (but not the DataField or DataValue). I want the item to appear grey if the item  is disabled (state in db) and black if not.My first thought was I could us the OnItemDataBind event to check the value and set the style... but there isn't one on a dropdownlist.My next thought was I could build a new component based on the dropdownlist and add a new property to the items "DataStateField" then check this on the rendering of the control, so the code might look a bit like...

How to set DDL's selected value by datasource other than DDL's datasource
I have three TemplateFields in a Gridview. In each, the ItemTemplate has a label whose text value is bound to the GridView's DataSource. But in the EditItemTemplate the DropDownList is populated with a separate DataSource. This is a fairly common setup, so that wasn't too much to deal with. What I need to do is, when the GridView goes in to Edit mode and the DropDownList is populated and displayed I want the value that was in the bound label to be the default selected value in the DropDownList. As it currently is, the DropDownList renders with "Select..." as the defau...

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

How to call an 'all' items value using a dropdownlist controlled by both a datasource and user defined values
Hi all, I have an access database datasource controlling a dropdown menu that i want to use in combination with a datalist controlled by another datasource (same database) to bring up results.   So far the user can select an option from my frontend menu which brings up the results in the datalist using a where statement which works fine. When i attached the dropdown menu using another 'where' statement i can use it to select the other values in the dropdown menu and the results are ammended correctly which is exactly what i want. The simple problem is...

Can default selected value be set for user?: EntityRef dropdown list on insert detailsview
I'd like for the user to be able to change the selected value in the dropdown list, if the choose to, prior to clicking "Insert". I'm just wondering if instead of having the dropdown list default to "Not Set", I can have the dropdown list default to a particular value.This is a case where, although there are five items in the table(and thus dropdown list), one of the items is used 97% of the time for inserts. Can this be done completely within my MetaData.cs file?  or do I need to use a custom fieldtemplate? The DefaultValue attribute should work for you ...

DataGrid
Hello, I'd like to set the value of a DropDownList based on a value of another field in the DataGrid.These values are from different <columns>.The first value shows up just fine in the "BoundColumn".But, the one I want to set in the TemplateColumn isn't working.Can someone take a look at my code snippet and see what I'm doing wrong? The Control I'm trying to set is called "ddlBenchStart".I'm trying to get the value from the "BenchStart" column.The values in "BenchStart" would be "Bench" or "Start&...

Setting a dropdownlist value based on a value in a Database
I have a page that allows users to create a user account. The aspx has various dropdowns that I populate by binding the dropdownlist to a dataset. OK so far? However, I also want a page where the user can edit their profile..so I need to be able to set the selected value based on what is saved in my user table and I also need to add the extra entries. Anyone know how I can do this easily. Do I need to join on my user table and my table that has all the various categories in order to get the selected value and add my other values?? Thanks, COG. For selecting the correct...

Setting a label value to a dropdownlist selected value
I am trying to set the value of a label to the selected value from a hidden dropdown list. This code is not working and the label value remians at its default. Any ideas? Thanks very much. Protected Sub DetailsView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Dim mylabel As Label Dim myddl As DropDownList If (DetailsView1.CurrentMode = DetailsViewMode.ReadOnly) Then mylabel = DetailsView1.FindControl("Label1") myddl = DetailsView1.FindControl("DropDownListViewOffice") mylabel.Text = myddl.SelectedValue.ToString End If I have now put this code in the Page_Load su...

Can set inital value for dropdownlists, but can't change them
I don't fully understand this. In Page_Load, I set the .SelectedValue for dropdownlists and listboxes so when a user logs in, logical defaults are already set. However, if the user then changes the items or shift-clicks new ones, and later I iterate over all the selected elements, only the one I set in Page_Load is returned. Same with dropdownlists. You can change it visually, but if I do DDL.SelectedValue, I am returned the original one I set myself. I don't really understand this behavior or how to fix it.  Can you post the code (.aspx and .aspx.cs)? I guess you have t...

Web resources about - Can a DataSource set the default value in a DropDownList (or the list fetch the value from a DataSource)? - asp.net.web-forms

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: 12/23/2015 6:02:42 AM