How to use a QueryString to set the value of a databound DropDownList

Last post 05-17-2007 9:19 AM by mychucky. 19 replies.

Sort Posts:

  • How to use a QueryString to set the value of a databound DropDownList

    01-19-2007, 10:59 AM
    • Loading...
    • JPortnoy
    • Joined on 08-01-2006, 1:33 PM
    • Posts 39

    I currently have a DropDownList that's values are populated from an ObjectDataSource. I'd like the ability to use the QueryString of the URL to set the value of this DropDownList (example: www.foo.com/sort.aspx?name=John).

     Is there some type of method for a DropDownList that allows you to set its value if it's databound?

     

    Thanks in advance.
     

  • Re: How to use a QueryString to set the value of a databound DropDownList

    01-19-2007, 11:20 AM
    • Loading...
    • Haissam
    • Joined on 10-05-2006, 2:25 AM
    • Beirut - Lebanon
    • Posts 4,682

    do u mean that if depending of the value in the query string to select that value from the ddl?

     

    Haissam Abdul Malak
    MCAD.NET
    | Blog |
  • Re: How to use a QueryString to set the value of a databound DropDownList

    01-19-2007, 11:29 AM
    • Loading...
    • tont
    • Joined on 11-20-2006, 8:45 PM
    • Posts 31

    Im not sure if this is what you want to do but so ill answer based on what i think you want to do :P

     

    you can actually skip the objectdatasource method if you like, and just put it in your page_load function. what i would do is something like create a list of your objects based on your parameter value. ie:

      

     protected void Page_Load(object sender, EventArgs e)
        {
            string name = Request["name"] as string;
            List list = people_handler.getPeople(name); 
            dropdownlist.datasource = list;
            dropdownlist.databind();
        }

     

    then in your asp file have something liek this:

     

    <asp:DropDownList id="dropdownlist" runat="server" DataTextField='FirstName' DataValueField='id'></asp:DropDownList>

      

     this is also assuming you have the fields 'FirstName' and 'id' in your dataobject.

     

    Hope that helps!
     

  • Re: How to use a QueryString to set the value of a databound DropDownList

    01-19-2007, 2:19 PM
    • Loading...
    • JPortnoy
    • Joined on 08-01-2006, 1:33 PM
    • Posts 39

    Yes, depending on the value of the QueryString, it should select that value in the DDL. I thought I could use this:

        ddl.Items.FindByValue("MyName").Selected = True

     However, this gives me a "Object reference not set to an instance of an object." error.

     

    I think the problem may lie that the values of the DDL are generated from the database?

     

    Any more suggestions?
     

     

  • Re: How to use a QueryString to set the value of a databound DropDownList

    01-19-2007, 8:54 PM
    Answer
    • Loading...
    • Haissam
    • Joined on 10-05-2006, 2:25 AM
    • Beirut - Lebanon
    • Posts 4,682

    Dear,

    if it's depending on the query string i got you what you want

    first get the value from the query string and save it into a string variable

    string id = Request.QueryString["id"];  (suppose you save it in the query string in id variable (?id=))

    then create a ListItem object and send the id as the string and the value (if the value and text in the ddl has the same string)

    ListItem item =

    new ListItem(id,id);

    then get the index of the value passed in the query string inside the ddl

    int

    z = DropDownList1.Items.IndexOf(item);

    then select the item with this index

    DropDownList1.Items[z].Selected =

    true;

    so your code finally will look like

    string id = Request.QueryString["id"];

    ListItem item =

    new ListItem(id,id);

    int z = DropDownList1.Items.IndexOf(item);

    DropDownList1.Items[z].Selected = true;

     

    Happy Coding

    Haissam Abdul Malak
    MCAD.NET
    | Blog |
  • Re: How to use a QueryString to set the value of a databound DropDownList

    01-22-2007, 1:55 AM
    Answer
    Hi,
    did you set its DataValueField property? It will correlate the dropdownlist item's value with a field in the datasource.
    Here is a sample.

    System.Data.SqlClient.SqlDataAdapter ada = new System.Data.SqlClient.SqlDataAdapter("select * from employees",
    System.Web.Configuration.WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
    DataSet ds = new DataSet();
    ada.Fill(ds);
    DropDownList1.DataSource = ds;
    DropDownList1.DataMember = ds.Tables[0].TableName;
    DropDownList1.DataTextField = "Title";
    DropDownList1.DataValueField = "City";
    DropDownList1.DataBind();

  • Re: How to use a QueryString to set the value of a databound DropDownList

    01-22-2007, 3:13 PM
    Answer
    • Loading...
    • PeterBrunone
    • Joined on 06-19-2002, 9:15 AM
    • I'm standing behind you.
    • Posts 3,663
    • TrustedFriends-MVPs
    JPortnoy:
    I thought I could use this:

        ddl.Items.FindByValue("MyName").Selected = True

     However, this gives me a "Object reference not set to an instance of an object." error.


    Make sure that (a) the value from the querystring is what you expect, and that (b) you're not trying to select an item that isn't there.  The latter can happen because the value doesn't exist in your list, OR because you haven't actually databound the list yet (so it contains no items).

     

    Peter Brunone
    MS MVP, ASP.NET
    Founder, EasyListBox.com
    Do the impossible, and go home early.
  • Re: How to use a QueryString to set the value of a databound DropDownList

    01-22-2007, 5:11 PM
    Answer

    Have a look at this example I have created for you, it works with SqlDataSource, but you will use the same idea with ObjectDataSource:

            <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2"
                DataTextField="FirstName" DataValueField="ContactID">
            </asp:DropDownList>
            <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" 
                SelectCommand="SELECT TOP 5 [ContactID], [FirstName] FROM Person.Contact">
            </asp:SqlDataSource>
    

     

    In the code behind you add this:

        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {
            // Make sure you run this code inly when there is a valid QueryString
            if (!string.IsNullOrEmpty(Request.QueryString["ContactID"]))
            {
                // Retrieve the QueryString
                string contactID = Request.QueryString["ContactID"].ToString();
    
    
                // If the QueryString value is among the loaded items in the
                // DropDownList, select it.
                ListItem lt = this.DropDownList1.Items.FindByValue(contactID);
                if (lt != null)
                    lt.Selected = true;
            }
        }

     

    You would call tha page for example with http://localhost/web/page.aspx?ContactId=3 and it will select the 3rd record for you in the DDL. If you skip the ContactID in the query string, it will show the first item in the DDL as the selected one!

    Hope this helps!
    Regards

    Bilal Hadiar, MCP, MCTS, MCPD, MCT
    Microsoft MVP - Telerik MVP
  • Re: How to use a QueryString to set the value of a databound DropDownList

    05-16-2007, 11:45 AM

    haidar_bilal:

    Have a look at this example I have created for you, it works with SqlDataSource, but you will use the same idea with ObjectDataSource:

            <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2"
                DataTextField="FirstName" DataValueField="ContactID">
            </asp:DropDownList>
            <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" 
                SelectCommand="SELECT TOP 5 [ContactID], [FirstName] FROM Person.Contact">
            </asp:SqlDataSource>
    

     

    In the code behind you add this:

        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {
            // Make sure you run this code inly when there is a valid QueryString
            if (!string.IsNullOrEmpty(Request.QueryString["ContactID"]))
            {
                // Retrieve the QueryString
                string contactID = Request.QueryString["ContactID"].ToString();
    
    
                // If the QueryString value is among the loaded items in the
                // DropDownList, select it.
                ListItem lt = this.DropDownList1.Items.FindByValue(contactID);
                if (lt != null)
                    lt.Selected = true;
            }
        }

     

    You would call tha page for example with http://localhost/web/page.aspx?ContactId=3 and it will select the 3rd record for you in the DDL. If you skip the ContactID in the query string, it will show the first item in the DDL as the selected one!

    Hope this helps!
    Regards

    Has anyone actually try this to see if it works? I tried it and it's not working and when I go into debug mode I see why it doesn't work. The ListItem lt will always equal to null because there is no data loaded into the DropDownList so FindByValue will always get a null value back. I tried the Page_PreRender, Page_Load, DropDownList databind, databound, load and notihng has worked. What I need a is moment after the data has been loaded into the DropDownList then I can make the DDL select the value based on my QueryString ID. However, I have not been able to find where exactly that moment is in the code so I execute my code to select that item in the DDL.

  • Re: How to use a QueryString to set the value of a databound DropDownList

    05-16-2007, 3:16 PM

    What is the problem? Can you email me please to: bhaidar@gmail.com?

     

    Thanks

    Bilal Hadiar, MCP, MCTS, MCPD, MCT
    Microsoft MVP - Telerik MVP
  • Re: How to use a QueryString to set the value of a databound DropDownList

    05-16-2007, 3:34 PM

    I already stated the problem in my previous post. I setup my method and dropdownlist control exactly as described and it's not working. The item in the DDL is not getting selected. However, thanks to e-screw from another thread I have, I was able to solved the problem...but not under the Page_PreRender method and not using the code you suggested above. It would be really nice if your code works...because it is neat and easy to understand.

    This is what I have and it is now working.

     

    1    protected void DropDownList1_DataBound(object sender, EventArgs e)
    2        {
    3            if (!String.IsNullOrEmpty(Request.QueryString["ID"]))
    4            {
    5                string strID = Request.QueryString["ID"];
    6                //gets the index of the selected items by finding it through value
    7                int index = Convert.ToInt32(DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(strID)));
    8                if (index == -1)
    9                {
    10                   MessageBox.Show("No item with index " + index + " are found");
    11               }
    12               else
    13               {
    14                   DropDownList1.SelectedIndex = index;
    15               }
    16           }
    17       }
    
      

     

    However, many
  • Re: How to use a QueryString to set the value of a databound DropDownList

    05-16-2007, 3:34 PM

    I already stated the problem in my previous post. I setup my method and dropdownlist control exactly as described and it's not working. The item in the DDL is not getting selected. However, thanks to e-screw from another thread I have, I was able to solved the problem...but not under the Page_PreRender method and not using the code you suggested above. It would be really nice if your code works...because it is neat and easy to understand.

    This is what I have and it is now working.

     

    1    protected void DropDownList1_DataBound(object sender, EventArgs e)
    2        {
    3            if (!String.IsNullOrEmpty(Request.QueryString["ID"]))
    4            {
    5                string strID = Request.QueryString["ID"];
    6                //gets the index of the selected items by finding it through value
    7                int index = Convert.ToInt32(DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(strID)));
    8                if (index == -1)
    9                {
    10                   MessageBox.Show("No item with index " + index + " are found");
    11               }
    12               else
    13               {
    14                   DropDownList1.SelectedIndex = index;
    15               }
    16           }
    17       }
    
      

     

    However, many thanks
  • Re: How to use a QueryString to set the value of a databound DropDownList

    05-16-2007, 3:34 PM

    I already stated the problem in my previous post. I setup my method and dropdownlist control exactly as described and it's not working. The item in the DDL is not getting selected. However, thanks to e-screw from another thread I have, I was able to solved the problem...but not under the Page_PreRender method and not using the code you suggested above. It would be really nice if your code works...because it is neat and easy to understand.

    This is what I have and it is now working.

     

    1    protected void DropDownList1_DataBound(object sender, EventArgs e)
    2        {
    3            if (!String.IsNullOrEmpty(Request.QueryString["ID"]))
    4            {
    5                string strID = Request.QueryString["ID"];
    6                //gets the index of the selected items by finding it through value
    7                int index = Convert.ToInt32(DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(strID)));
    8                if (index == -1)
    9                {
    10                   MessageBox.Show("No item with index " + index + " are found");
    11               }
    12               else
    13               {
    14                   DropDownList1.SelectedIndex = index;
    15               }
    16           }
    17       }
    
      

     

    However, many thanks to your
  • Re: How to use a QueryString to set the value of a databound DropDownList

    05-16-2007, 3:34 PM

    I already stated the problem in my previous post. I setup my method and dropdownlist control exactly as described and it's not working. The item in the DDL is not getting selected. However, thanks to e-screw from another thread I have, I was able to solved the problem...but not under the