DropDownList binding SelectedValue

Last post 09-25-2009 12:18 AM by altafkhatri@hotmail.com. 15 replies.

Sort Posts:

  • DropDownList binding SelectedValue

    01-08-2005, 8:11 PM
    • Member
      270 point Member
    • weiwei99
    • Member since 07-25-2002, 8:54 AM
    • Posts 54
    Hi everybody,

    I have a DropDownList, I can bind it to a table and populate its choice items.
    But at the same time I want to bind it to another table to set the SelectedValue.
    A good example is a dropdownlist allowing a user to choose a state from all the states.
    How can I bind the selectedvalue to the database?




    Thank you.


    Henry
  • Re: DropDownList binding SelectedValue

    01-09-2005, 3:20 AM
    • All-Star
      29,632 point All-Star
    • Fredrik N
    • Member since 06-22-2002, 5:03 AM
    • Sweden
    • Posts 5,333
    • TrustedFriends-MVPs
    If you use another data-bound control such as the FormView or DetailsView to bind the user's information, you could use the Bind expression to set the SelectedValue based on a value returned from the data-source control that is associated with the FormView or DetailsView control:

    <asp:DropDownList SelectedValue='<%# Bind("State")%>' ....>

    The Sate in the example above, is the field returned from the SelectCommand specified for the DetailsView, FormView or other data-bound control.
    /Fredrik Normén - fredrikn @ twitter

    Microsoft MVP, MCSD, MCAD, MCT

    ASPInsiders
    My Blog
  • Re: DropDownList binding SelectedValue

    01-09-2005, 9:23 AM
    • Member
      270 point Member
    • weiwei99
    • Member since 07-25-2002, 8:54 AM
    • Posts 54
    Hi Fredrik,

    SelectedValue cannot be set at design time, this is the error message I get if I put in:
    <asp:DropDownList SelectedValue='<%# Bind("State")%>' ....>

    Error Message:
    The 'SelectedValue' property can only be set programmatically. It cannot be declared.

    Moreover, a DropDownList (or a ListBox) can only be bound to one datasource.
    I have to use this datasource to populate the choice item with records from a lookup table.
    Now, if I want to bind its SelectedValue to another table containing users selection, it seems to be imposssible.

    Am I right?

    Thank you.
  • Re: DropDownList binding SelectedValue

    01-09-2005, 10:10 AM
    • All-Star
      29,632 point All-Star
    • Fredrik N
    • Member since 06-22-2002, 5:03 AM
    • Sweden
    • Posts 5,333
    • TrustedFriends-MVPs
    Take a look at the following Example (It uses the Northwind database) that will get data from one data-source control and also fill a DropDownList by using another data-source control. The SelectedValue is bound to the ContactTitle value returned form the first data-source control. The value bind to the DropDownList SelectedValue, must be located within the DropDownList, if not an exception will be thrown:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default_aspx" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
    <title>Untitled Page</title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <asp:FormView DataKeyNames="CustomerID" DataSourceID="SqlDataSource1" ID="FormView1"
    runat="server">
    <EditItemTemplate>
    CustomerID:
    <asp:Label ID="CustomerIDLabel1" runat="server" Text='<%# Eval("CustomerID") %>'></asp:Label>
    <br />
    CompanyName:
    <asp:TextBox ID="CompanyNameTextBox" runat="server" Text='<%# Bind("CompanyName") %>'></asp:TextBox><br />
    ContactName:
    <asp:TextBox ID="ContactNameTextBox" runat="server" Text='<%# Bind("ContactName") %>'></asp:TextBox><br />
    ContactTitle:
    <asp:DropDownList SelectedValue='<%# Bind("ContactTitle") %>' DataSourceID="SqlDataSource1" DataTextField="ContactTitle" DataValueField="ContactTitle"
    ID="DropDownList1" runat="server">
    </asp:DropDownList><asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
    ID="SqlDataSource1" runat="server" SelectCommand="SELECT DISTINCT [ContactTitle] FROM [Customers]">
    </asp:SqlDataSource>
    <br />
    <asp:LinkButton CausesValidation="True" CommandName="Update" ID="UpdateButton" runat="server"
    Text="Update"></asp:LinkButton>
    &nbsp;<asp:LinkButton CausesValidation="False" CommandName="Cancel" ID="UpdateCancelButton"
    runat="server" Text="Cancel"></asp:LinkButton>
    </EditItemTemplate>
    <ItemTemplate>
    CustomerID:
    <asp:Label ID="CustomerIDLabel" runat="server" Text='<%# Eval("CustomerID") %>'>
    </asp:Label>
    <br />
    CompanyName:
    <asp:Label ID="CompanyNameLabel" runat="server" Text='<%# Bind("CompanyName") %>'>
    </asp:Label>
    <br />
    ContactName:
    <asp:Label ID="ContactNameLabel" runat="server" Text='<%# Bind("ContactName") %>'>
    </asp:Label>
    <br />
    ContactTitle:
    <asp:Label ID="ContactTitleLabel" runat="server" Text='<%# Bind("ContactTitle") %>'>
    </asp:Label>
    <br />
    <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
    </ItemTemplate>
    </asp:FormView>
    <asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
    ID="SqlDataSource1" runat="server"
    SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle] FROM [Customers]"
    UpdateCommand="UPDATE [Customers] SET [CompanyName] = @CompanyName, [ContactName] = @ContactName, [ContactTitle] = @ContactTitle WHERE [CustomerID] = @original_CustomerID">

    </asp:SqlDataSource>

    </div>
    </form>
    </body>
    </html>
    /Fredrik Normén - fredrikn @ twitter

    Microsoft MVP, MCSD, MCAD, MCT

    ASPInsiders
    My Blog
  • Re: DropDownList binding SelectedValue

    01-09-2005, 11:58 AM
    • Member
      270 point Member
    • weiwei99
    • Member since 07-25-2002, 8:54 AM
    • Posts 54
    Fredrik,

    It works!
    Thank you very much.
    You helped me solved two problems.
    Thanks again.



    Regards,

    Henry
  • Re: DropDownList binding SelectedValue

    01-10-2005, 12:41 PM
    • Member
      70 point Member
    • gregkats
    • Member since 06-18-2002, 6:05 AM
    • Posts 15
    Fredrik,

    I am trying to do the same thing with ObjectDataSources instead of SQLDataSources. But I keep getting the error "Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control."

    It only occurs when I try to Bind the SelectedValue of a DropDownList.

    [code]
    <asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
    <asp:FormView DataSourceID="ObjectDataSource1" ID="FormView1" runat="server" Caption="Contact" DefaultMode="Insert" >
    <InsertItemTemplate>
    <table cellpadding="0" cellspacing="0" border="0">
    <tr>
    <td>
    First Name:
    </td>
    <td>
    <asp:TextBox ID="txtContactFirstName" runat="server" Text='<%# Bind("ContactFirstName") %>'></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    Last Name:
    </td>
    <td>
    <asp:TextBox ID="txtContactLastName" runat="server" Text='<%# Bind("ContactLastName") %>'></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    Company:
    </td>
    <td>
    <asp:DropDownList ID="ddlCompany" DataSourceID="ObjectDataSource2" SelectedValue='<%# Bind("ContactCompanyID") %>' DataValueField="CompanyID" DataTextField="CompanyName" runat="server"></asp:DropDownList>
    </td>
    </tr>
    <tr>
    <td colspan="2" align="Center">
    <asp:ImageButton ID="btnSave" CommandName="Insert" runat="server" SkinID="add" />
    </td>
    </tr>
    </table>
    </InsertItemTemplate>
    <EditItemTemplate>
    <table cellpadding="0" cellspacing="0" border="0">
    <tr>
    <td>
    First Name:
    </td>
    <td>
    <asp:TextBox ID="txtContactFirstName" runat="server" Text='<%# Bind("ContactFirstName") %>'></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    Last Name:
    </td>
    <td>
    <asp:TextBox ID="txtContactLastName" runat="server" Text='<%# Bind("ContactLastName") %>'></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    Company:
    </td>
    <td>
    <asp:DropDownList ID="ddlCompany" DataSourceID="ObjectDataSource2" SelectedValue='<%# Bind("ContactCompanyID") %>' DataValueField="CompanyID" DataTextField="CompanyName" runat="server"></asp:DropDownList>
    </td>
    </tr>
    <tr>
    <td colspan="2" align="Center">
    <asp:ImageButton ID="btnSave" runat="server" CommandName="Update" SkinID="save" />&nbsp;<asp:ImageButton CausesValidation="false" ID="btnDelete" CommandName="Delete" runat="server" SkinID="delete" OnClientClick="if (!confirm('Are You Sure You Want To Delete This Item')){return false}"/>
    </td>
    </tr>
    </table>
    </EditItemTemplate>
    </asp:FormView>
    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="Retrieve" DeleteMethod="Delete" InsertMethod="Insert" UpdateMethod="Update" TypeName="Contact"></asp:ObjectDataSource>
    <asp:ObjectDataSource ID="ObjectDataSource2" runat="server" SelectMethod="ListAll" TypeName="Companies"></asp:ObjectDataSource>
    </asp:Content>

    [/code]

    Have you been able to get this to work or is this a Bug with the ObjectDataSource code? I am using November CTP.

    TIA
  • Re: DropDownList binding SelectedValue

    01-10-2005, 4:42 PM
    • Contributor
      2,680 point Contributor
    • phuff
    • Member since 06-11-2002, 12:39 PM
    • Redmond, WA
    • Posts 547
    • AspNetTeam
    You're getting this error because you have bindings (Bind statements, Evals, etc.) in your InsertItemTemplate of the FormView. FormView isn't databound in Insert mode (there's no current data item in Insert mode- you're attempting to create the item, so you get just un-databound controls) so the control doesn't have an item to reference for the databindings.

    Are you trying to put default values into the Insert form? You should just set the Text and SelectedIndex properties directly instead of using a data item. If you need to use a record from your database as the default value source, I advise that you handle the OnModeChanging, see if it's changing to Insert, and copy your default record to a new record in your database, then change the NewMode to edit the new record.

    If you don't need default values in your Insert form, just remove the bindings and everything should work fine.

    Hope this helps...
    Polita Paulus

    This posting is provided "AS IS" with no warranties, and confers no rights.
  • Re: DropDownList binding SelectedValue

    01-11-2005, 12:26 AM
    • All-Star
      29,632 point All-Star
    • Fredrik N
    • Member since 06-22-2002, 5:03 AM
    • Sweden
    • Posts 5,333
    • TrustedFriends-MVPs
    The following example uses the InsertItemTemplate, where the Bind expression is used on DropDownList SelectedValue to make sure the selected value is passed to into input parameter. The code uses the SqlDataSource control, but this should work for the ObjectDataSOurce control also.


    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default_aspx" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <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:FormView DataKeyNames="CustomerID" DefaultMode=Insert DataSourceID="SqlDataSource1" ID="FormView1"
    runat="server">
    <InsertItemTemplate>
    CustomerID:
    <asp:TextBox ID="CustomerID" runat="server" Text='<%# Bind("CustomerID") %>'></asp:TextBox><br />
    CompanyName:
    <asp:TextBox ID="CompanyNameTextBox" runat="server" Text='<%# Bind("CompanyName") %>'></asp:TextBox><br />
    ContactName:
    <asp:TextBox ID="ContactNameTextBox" runat="server" Text='<%# Bind("ContactName") %>'></asp:TextBox><br />
    ContactTitle:
    <asp:DropDownList SelectedValue='<%# Bind("ContactTitle") %>' DataSourceID="SqlDataSource1" DataTextField="ContactTitle" DataValueField="ContactTitle"
    ID="DropDownList1" runat="server">
    </asp:DropDownList><asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
    ID="SqlDataSource1" runat="server" SelectCommand="SELECT DISTINCT [ContactTitle] FROM [Customers]">
    </asp:SqlDataSource>
    <br />
    <asp:LinkButton CausesValidation="True" CommandName="Insert" ID="InsertButton" runat="server"
    Text="Insert"></asp:LinkButton>
    &nbsp;<asp:LinkButton CausesValidation="False" CommandName="Cancel" ID="CancelButton"
    runat="server" Text="Cancel"></asp:LinkButton>
    </InsertItemTemplate>
    <ItemTemplate>
    CustomerID:
    <asp:Label ID="CustomerIDLabel" runat="server" Text='<%# Eval("CustomerID") %>'>
    </asp:Label>
    <br />
    CompanyName:
    <asp:Label ID="CompanyNameLabel" runat="server" Text='<%# Bind("CompanyName") %>'>
    </asp:Label>
    <br />
    ContactName:
    <asp:Label ID="ContactNameLabel" runat="server" Text='<%# Bind("ContactName") %>'>

    </asp:Label>
    <br />
    ContactTitle:
    <asp:Label ID="ContactTitleLabel" runat="server" Text='<%# Bind("ContactTitle") %>'>
    </asp:Label>
    <br />
    <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
    </ItemTemplate>
    </asp:FormView>
    <asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
    ID="SqlDataSource1" runat="server" SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle] FROM [Customers]"
    InsertCommand="INSERT INTO [Customers] ([CustomerID],[CompanyName], [ContactName], [ContactTitle]) VALUES (@CustomerID, @CompanyName, @ContactName, @ContactTitle)">
    </asp:SqlDataSource>
    </div>
    </form>
    </body>
    </html>
    /Fredrik Normén - fredrikn @ twitter

    Microsoft MVP, MCSD, MCAD, MCT

    ASPInsiders
    My Blog
  • Re: DropDownList binding SelectedValue

    01-11-2005, 7:14 AM
    • Member
      70 point Member
    • gregkats
    • Member since 06-18-2002, 6:05 AM
    • Posts 15
    Phuff,

    I don't think the InsertItemTemplate really has anything to do with the problem. It doesn't work even if it's in EditMode. Besides that, the point of Binding form elements is so the FormView will handle the Update/Insert calls back to the datasource correctly. And Fredrik and others on this message board say they are getting it to work on SQLDataSources.

    Fredrik,

    The only difference I see in the code you posted and what I posted is you are using SQLDataSource and I am using ObjectDataSource. I have to assume there is an issue with binding the SelectedValue in an ObjectDataSource. If you see any other differences I would appreciate hearing about it.

    In the CodeFile, Page_Load method, I check for an ID in the QueryString and switch the mode of the FormView to Edit or Insert as appropriate.

    TIA
  • Re: DropDownList binding SelectedValue

    01-11-2005, 7:57 AM
    • All-Star
      29,632 point All-Star
    • Fredrik N
    • Member since 06-22-2002, 5:03 AM
    • Sweden
    • Posts 5,333
    • TrustedFriends-MVPs
    Here is a working example, that uses the ObejctDataSource:

    Default.aspx


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

    <script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
    if (Request.QueryString["Mode"] == "Insert")
    FormView1.DefaultMode = FormViewMode.Insert;
    else
    FormView1.DefaultMode = FormViewMode.ReadOnly;
    }
    </script>

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
    <title>Untitled Page</title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <asp:FormView DataSourceID="ObjectDataSource1"
    ID="FormView1" runat="server">
    <InsertItemTemplate>
    CustomerName:
    <asp:TextBox ID="CustomerNameTextBox" runat="server" Text='<%# Bind("CustomerName") %>'></asp:TextBox><br />
    CustomerTitle:
    <asp:DropDownList SelectedValue='<%# Bind("CustomerTitle") %>' DataSourceID="ObjectDataSource1" ID="DropDownList1" runat="server">
    </asp:DropDownList>
    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetAllTitles"
    TypeName="CustomerRepository"></asp:ObjectDataSource>
    <br />
    <asp:LinkButton CausesValidation="True" CommandName="Insert" ID="InsertButton" runat="server"
    Text="Insert"></asp:LinkButton>
    &nbsp;<asp:LinkButton CausesValidation="False" CommandName="Cancel" ID="InsertCancelButton"
    runat="server" Text="Cancel"></asp:LinkButton>
    </InsertItemTemplate>
    <ItemTemplate>
    CustomerName:
    <asp:Label ID="CustomerNameLabel" runat="server" Text='<%# Eval("CustomerName") %>'>
    </asp:Label>
    <br />
    CustomerID:
    <asp:Label ID="CustomerIDLabel" runat="server" Text='<%# Eval("CustomerID") %>'>
    </asp:Label>
    <br />
    CustomerTitle:
    <asp:Label ID="CustomerTitleLabel" runat="server" Text='<%# Eval("CustomerTitle") %>'>
    </asp:Label>
    <br />
    <asp:LinkButton CausesValidation="False" CommandName="New" ID="InsertButton" runat="server"
    Text="Insert">
    </asp:LinkButton>
    </ItemTemplate>
    </asp:FormView>
    <asp:ObjectDataSource DataObjectTypeName="Customer" ID="ObjectDataSource1" runat="server"
    SelectMethod="GetAll"
    TypeName="CustomerRepository"
    InsertMethod="Insert"></asp:ObjectDataSource>
    &nbsp;
    </div>
    </form>
    </body>
    </html>

    CustomerRespository.cs

    public class CustomerRepository
    {
    public CustomerRepository()
    {
    }

    public IList<Customer> GetAll()
    {
    IList<Customer> customers = new List<Customer>();

    customers.Add(new Customer(1, "Fredrik", "Developer"));
    customers.Add(new Customer(2, "Johan", "Developer"));
    customers.Add(new Customer(3, "Lovisa", "Product Manager"));
    customers.Add(new Customer(4, "Anna", "Program Manager"));

    return customers;
    }

    public void Insert(Customer customer)
    {
    }

    public void Insert(string customerName, string customerTitle)
    {
    }

    public string[] GetAllTitles()
    {
    return new string[] { "Developer", "Product Manager", "Program Manager" };
    }
    }

    Customer.cs

    public class Customer
    {
    private int _customerId;
    private string _customerName;
    private string _customerTitle;

    public Customer()
    {
    }

    public Customer(int customerId, string customerName, string customerTitle)
    {
    this._customerId = customerId;
    this._customerName = customerName;
    this.CustomerTitle = customerTitle;
    }

    public int CustomerID
    {
    get { return this._customerId; }
    internal set { this._customerId = value; }
    }

    public string CustomerName
    {
    get { return this._customerName; }
    set { this._customerName = value; }
    }

    public string CustomerTitle
    {
    get { return this._customerTitle; }
    set { this._customerTitle = value; }
    }
    }
    /Fredrik Normén - fredrikn @ twitter

    Microsoft MVP, MCSD, MCAD, MCT

    ASPInsiders
    My Blog
  • Re: DropDownList binding SelectedValue

    01-11-2005, 8:07 AM
    • Member
      70 point Member
    • gregkats
    • Member since 06-18-2002, 6:05 AM
    • Posts 15
    Fredrik,

    Thanks for the code! The only question I have is I don't understand how the code can work as posted because you have two ObjectDataSource controls named ObjectDataSource1. I assume that is just a typo.

    Thanks
  • Re: DropDownList binding SelectedValue

    01-11-2005, 8:14 AM
    • All-Star
      29,632 point All-Star
    • Fredrik N
    • Member since 06-22-2002, 5:03 AM
    • Sweden
    • Posts 5,333
    • TrustedFriends-MVPs
    It actually work, because the other data source is located whiten the template of the FormView. But I should have different name, to make it easier to identity the two data source. I didn't care about that when I created the example for you.
    /Fredrik Normén - fredrikn @ twitter

    Microsoft MVP, MCSD, MCAD, MCT

    ASPInsiders
    My Blog
  • Re: DropDownList binding SelectedValue

    01-11-2005, 8:56 AM
    • Member
      70 point Member
    • gregkats
    • Member since 06-18-2002, 6:05 AM
    • Posts 15
    OK.

    So the lesson learned here is the DataSource Control for binding the SelectedItem needs to be inside the Template of the FormView Control and the DataSource Control for the FormView Control needs to be outside the FormView Control.

    It works now.

    Thanks
  • Re: DropDownList binding SelectedValue

    01-12-2005, 9:08 AM
    • Member
      70 point Member
    • gregkats
    • Member since 06-18-2002, 6:05 AM
    • Posts 15
    I have finally found the problem I have been having in this process.

    Here is what I finally came up with. If, during Page_Load, I use either of the following lines I get the error mentioned below about binding the selected item:


    this.FormView1.FindControl("SomeFieldName").Focus();
    this.Form.DefaultButton = ((ImageButton)this.FormView1.FindControl("SomeButtonName")).UniqueID;


    If I comment out those two lines the bind of the page works correctly. If I don't have a DropDownList that I need to bind the SelectedValue on the page I can use those lines just fine. I don't know why this is a problem. But it happens 100% of the time for me. I don't know if it's a problem with anything other than the ObjectDataSource or Not.

    Again this is the November CTP.
  • Re: DropDownList binding SelectedValue

    05-02-2005, 8:57 PM
    • Member
      20 point Member
    • h8899
    • Member since 05-01-2005, 12:17 AM
    • Posts 4

    Dear Sir,

    Can we catch the exception on code behind?

     

     Fredrik N wrote:
    Take a look at the following Example (It uses the Northwind database) that will get data from one data-source control and also fill a DropDownList by using another data-source control. The SelectedValue is bound to the ContactTitle value returned form the first data-source control. The value bind to the DropDownList SelectedValue, must be located within the DropDownList, if not an exception will be thrown:


    " UpdateCommand="UPDATE [Customers] SET [CompanyName] = @CompanyName, [ContactName] = @ContactName, [ContactTitle] = @ContactTitle WHERE [CustomerID] = @original_CustomerID">
Page 1 of 2 (16 items) 1 2 Next >