Outside Computers

Sunday, October 14, 2012

Bind dynamically items in dropdownlists

In this tutorial I will show you how to bind items dynamically in dropdownlist.

in this example, i have used hyperlinks and bind the selected link in a single dropdownlist
I have used query string  for passing the value in the dropdownlist to show what items to be displayed.
you can also use session variables and also cookies for binding items on the list.

this is WebForm1.aspx

protected void Page_Load(object sender, EventArgs e)
        {
            createNavUrls();
        }
        private void createNavUrls()
        {
         
                HyperLink1.NavigateUrl = @"WebForm2.aspx?Option=1";
           
                HyperLink2.NavigateUrl = @"WebForm2.aspx?Option=2";
         
                HyperLink3.NavigateUrl = @"WebForm2.aspx?Option=3";
        }

this piece of code shows, when the page load, the code will call the createNavUrls(), that adds the navigate url links and shows the query string,, upon selecting on the links it has corresponding values,1,2,3 and the query string name is "Option".

WebForm2.aspx

 protected void Page_Load(object sender, EventArgs e)
        {
            filllist(Convert.ToInt32(Request.QueryString["Option"]));
        }
        private void filllist(int option)
        {
            ddlOptions.Items.Clear();
            if (option == 1)
            {
                ddlOptions.Items.Add("a1");
                ddlOptions.Items.Add("a2");
                ddlOptions.Items.Add("a3");
            }
            else if (option == 2)
            {
                ddlOptions.Items.Add("b4");
                ddlOptions.Items.Add("b5");
                ddlOptions.Items.Add("b6");
            }
            else if (option == 3)
            {
                ddlOptions.Items.Add("c7");
                ddlOptions.Items.Add("c8");
                ddlOptions.Items.Add("c9");
            }
        }

on the other hand, the second page will load, the selected hyperlink's value,

on the page load , the Request.QueryString["Option"], this will read the value given by the 1st page,
then on the method fill,  this will add the items that is selected on the desired input.

here is the sample url of the page.
"http://localhost:56594/WebForm2.aspx?Option=1"

Option is the querystring name and 1 is the value


i hope this code helps.






No comments:

Post a Comment