Click here to Skip to main content
14,489,986 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hello,

I have one problem. how can I copy one dropdownlist value to another?
For eg. I want to copy corresponding address details to permanent address by clicking on checkbox button. I have 3 dropdownlist in address for District,State and Country and i have dynamically fetched values in this dropdownlist.
Posted
Rate this:
Please Sign up or sign in to vote.

Solution 1

Hi Ashu

you need cascade dropdownlist

then we have a control in ajax cascadingdropdownlist you will use that
or else if you want from database means you will use this
it will work out you

using three tables country, state ,city
and you have to give a relation between country and state, state and city
you must mention the primary key and foreign key to the tables

and write acode like this
public partial class CountryDropdowns : System.Web.UI.Page
{
    string strcon = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindContrydropdown();
}

}
/// <summary>
/// Bind COuntrydropdown
/// </summary>
protected void BindContrydropdown()
{
//conenction path for database
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Counrty", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlCountry.DataSource = ds;
ddlCountry.DataTextField = "Country";
ddlCountry.DataValueField = "Id";
ddlCountry.DataBind();
ddlCountry.Items.Insert(0, new ListItem("--Select--", "0"));
ddlCity.Items.Insert(0, new ListItem("--Select--", "0"));
ddlState.Items.Insert(0, new ListItem("--Select--", "0"));

}
/// <summary>
/// Bind State Dropdown Based on CountryID
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
int Id = Convert.ToInt32(ddlCountry.SelectedValue);
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlCommand cmd = new SqlCommand("select * from City where Id="+Id, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlCity.DataSource = ds;
ddlCity.DataTextField = "City";
ddlCity.DataValueField = "CityId";
ddlCity.DataBind();
ddlCity.Items.Insert(0, new ListItem("--Select--", "0"));
if(ddlCity.SelectedValue=="0")
{
ddlState.Items.Clear();
ddlState.Items.Insert(0, new ListItem("--Select--", "0"));
}

}
/// <summary>
/// Bind Region dropdown based on Re
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
int CityId = Convert.ToInt32(ddlCity.SelectedValue);
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlCommand cmd = new SqlCommand("select * from State where CityId=" + CityId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlState.DataSource = ds;
ddlState.DataTextField = "State";
ddlState.DataValueField = "StateId";
ddlState.DataBind();
ddlState.Items.Insert(0, new ListItem("--Select--", "0"));
}
}

Thanks & Regards
Aswini Aluri
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 2

Hi,

Using Ajax Control Toolkit, You can do it in a so easy way.

Here is .aspx source code

Add AjaxControlToolkit as Register directive

<![CDATA[<%@ Register

    Assembly="AjaxControlToolkit"

    Namespace="AjaxControlToolkit"

    TagPrefix="ajaxToolkit" %>]]>


Then Do code as showing below

  <ajaxtoolkit:toolkitscriptmanager enablepartialrendering="true" runat="server" id="ScriptManager1" xmlns:ajaxtoolkit="#unknown" />
    <div class="demoarea">
        <div class="demoheading">CascadingDropDown Demonstration</div>
        <table>
            <tr>
                <td>Make</td>
                <td><asp:dropdownlist id="DropDownList1" runat="server" width="170" xmlns:asp="#unknown" /></td>
            </tr>
            <tr>
                <td>Model</td>
                <td><asp:dropdownlist id="DropDownList2" runat="server" width="170" xmlns:asp="#unknown" /></td>
            </tr>
            <tr>
                <td>Color</td>
                <td><asp:dropdownlist id="DropDownList3" runat="server" width="170" autopostback="true" xmlns:asp="#unknown">
                    OnSelectedIndexChanged="DropDownList3_SelectedIndexChanged" /></asp:dropdownlist></td>
            </tr>
        </table>
        <br />
        
        <ajaxtoolkit:cascadingdropdown id="CascadingDropDown1" runat="server" targetcontrolid="DropDownList1" xmlns:ajaxtoolkit="#unknown">
            Category="Make"  PromptText="Please select a make"  LoadingText="[Loading makes...]"
            ServicePath="CarsService.asmx" ServiceMethod="GetDropDownContents" />
        <ajaxtoolkit:cascadingdropdown id="CascadingDropDown2" runat="server" targetcontrolid="DropDownList2">
            Category="Model" PromptText="Please select a model" LoadingText="[Loading models...]"
            ServiceMethod="GetDropDownContentsPageMethod" ParentControlID="DropDownList1" />
        <ajaxtoolkit:cascadingdropdown id="CascadingDropDown3" runat="server" targetcontrolid="DropDownList3">
            Category="Color" PromptText="Please select a color" LoadingText="[Loading colors...]"
            ServicePath="~/CascadingDropDown/CarsService.asmx" ServiceMethod="GetDropDownContents"
            ParentControlID="DropDownList2" />
      
        <asp:updatepanel id="UpdatePanel1" runat="server" updatemode="Conditional" rendermode="inline" xmlns:asp="#unknown">
            <contenttemplate>
                <asp:label id="Label1" runat="server" text="[No response provided yet]" />
            </contenttemplate>
            <triggers>
                <asp:asyncpostbacktrigger controlid="DropDownList3" eventname="SelectedIndexChanged" />
            </triggers>
        </asp:updatepanel>
    </ajaxtoolkit:cascadingdropdown></ajaxtoolkit:cascadingdropdown></ajaxtoolkit:cascadingdropdown></div>
    <div class="demobottom"></div>
    
    <asp:panel id="Description_HeaderPanel" runat="server" style="cursor: pointer;" xmlns:asp="#unknown">
        <div class="heading">
            <asp:imagebutton id="Description_ToggleImage" runat="server" imageurl="~/images/collapse.jpg" alternatetext="collapse" />
            CascadingDropDown Description
        </div>
    </asp:panel>
    <asp:panel id="Description_ContentPanel" runat="server" style="overflow:hidden;" xmlns:asp="#unknown">
        <p>
            CascadingDropDown is an ASP.NET AJAX extender that can be attached to an ASP.NET DropDownList
            control to get automatic population of a set of DropDownList controls.  Each time the selection
            of one the DropDownList controls changes, the CascadingDropDown makes a call to a specified web
            service to retrieve the list of values for the next DropDownList in the set.
        </p>
        <br />
        <p>
            CascadingDropDown enables a common scenario in which the contents of one list depends on the selection 
            of another list and does so without having to embed the entire data set in the page or transfer it to 
            the client at all.
        </p>
        <br />
        <p>    
            All the logic about the contents of the set of DropDownList controls lives on the server in a web service. 
            This web service can use any suitable method for storing and looking up the relevant data.
        </p>
        <br />
        <p>    
            The sample web service used here reads the data set from a simple hierarchical XML data file. The 
            sample data file shows that the DropDownList items can have distinct names and value (values are 
            optional in the sample). It also demonstrates that items can have an optional optionTitle attribute 
            which will be displayed as a tooltip over the item in some modern browsers. Finally, an item can be 
            selected by default. In the XML file, the Racing Blue option for the BMW is selected by default.  
        </p>
        <br />
        <p>    
        There is also a walkthrough showing how to use a 
            <a href="../Walkthrough/CCDWithDB.aspx">CascadingDropDown with a database</a>.        
        </p>
    </asp:panel>

    <asp:panel id="Properties_HeaderPanel" runat="server" style="cursor: pointer;" xmlns:asp="#unknown">
        <div class="heading">
            <asp:imagebutton id="Properties_ToggleImage" runat="server" imageurl="~/images/expand.jpg" alternatetext="expand" />
            CascadingDropDown Properties
        </div>
    </asp:panel>
    <asp:panel id="Properties_ContentPanel" runat="server" style="overflow:hidden;" height="0px" xmlns:asp="#unknown">
        <p>
            The control above is initialized with this code. The italic properties are optional:
        </p>
<pre><ajaxToolkit:CascadingDropDown ID="CDD1" runat="server"

    TargetControlID="DropDownList2"

    Category="Model"

    PromptText="Please select a model"

    LoadingText="[Loading models...]"

    ServicePath="CarsService.asmx"

    ServiceMethod="GetDropDownContents"

    ParentControlID="DropDownList1"

    SelectedValue="SomeValue" />


  • TargetControlID - The ID of the DropDownList to populate.
  • Category - The name of the category this DropDownList represents.
  • PromptText - Optional text to display before the user has selected a value from the DropDownList.
  • PromptValue - Optional value set when PromptText is displayed.
  • EmptyText - Optional text to display when the DropDownList has no data to display.
  • EmptyValue - Optional value set when EmptyText is displayed.
  • LoadingText - Optional text to display while the data for the DropDownList
    is being loaded.
  • ServicePath - Path to a web service that returns the data used to populate
    the DropDownList. This property should be left null if ServiceMethod refers to a page method.
    The web service should be decorated with the System.Web.Script.Services.ScriptService
    attribute.
  • ServiceMethod - Web service method that returns the data used to populate
    the DropDownList. The signature of this method must match the following:
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public CascadingDropDownNameValue[] GetDropDownContents(
           string knownCategoryValues, string category) { ... }

    Note that you can replace "GetDropDownContents" with a naming of your choice, but the return
    type and parameter name and type must exactly match, including case.
  • ContextKey - User/page specific context provided to an optional overload of the
    web method described by ServiceMethod/ServicePath. If the context key is used, it should have the
    same signature with an additional parameter named contextKey of type string:
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public CascadingDropDownNameValue[] GetDropDownContents(
           string knownCategoryValues, string category, string contextKey) { ... }

    Note that you can replace "GetDropDownContents" with a name of your choice, but the return type
    and parameter name and type must exactly match, including case.
  • UseContextKey - Whether or not the ContextKey property should be used. This
    will be automatically enabled if the ContextKey property is ever set (on either the client or
    the server). If the context key is used, it should have the same signature with an additional
    parameter named contextKey of type string (as described above).
  • ParentControlID - Optional ID of the parent DropDownList that controls the
    contents of this DropDownList.
  • SelectedValue - Optional value to select by default. This needs to exactly
    match the string representation of a value in the DropDownList.
  • UseHttpGet - Optional value which determines whether to use HttpGet or HttpPost
    method for the postback to the server.
  • EnableAtLoading - Optional value which determines whether or not the dropdownlist
    control is disabled when the control is waiting to get data from the service.



<ajaxtoolkit:collapsiblepanelextender id="cpeDescription" runat="Server" xmlns:ajaxtoolkit="#unknown">
TargetControlID="Description_ContentPanel"
ExpandControlID="Description_HeaderPanel"
CollapseControlID="Description_HeaderPanel"
Collapsed="False"
ImageControlID="Description_ToggleImage" />
<ajaxtoolkit:collapsiblepanelextender id="cpeProperties" runat="Server">
TargetControlID="Properties_ContentPanel"
ExpandControlID="Properties_HeaderPanel"
CollapseControlID="Properties_HeaderPanel"
Collapsed="True"
ImageControlID="Properties_ToggleImage" />

.cs page code

protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Get selected values
        string make = DropDownList1.SelectedItem.Text;
        string model = DropDownList2.SelectedItem.Text;
        string color = DropDownList3.SelectedItem.Text;

        // Output result string based on which values are specified
        if (string.IsNullOrEmpty(make))
        {
            Label1.Text = "Please select a make.";
        }
        else if (string.IsNullOrEmpty(model))
        {
            Label1.Text = "Please select a model.";
        }
        else if (string.IsNullOrEmpty(color))
        {
            Label1.Text = "Please select a color.";
        }
        else
        {
            Label1.Text = string.Format("You have chosen a {0} {1} {2}. Nice car!", color, make, model);
        }
    }

    [WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static CascadingDropDownNameValue[] GetDropDownContentsPageMethod(string knownCategoryValues, string category)
    {
        return new CarsService().GetDropDownContents(knownCategoryValues, category);
    }


Web Method for some Items in DropDownList

using System;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Services;
using System.Xml;

/// <summary>
/// Helper web service for CascadingDropDown sample
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class CarsService : WebService
{
    // Member variables
    private static XmlDocument _document;
    private static Regex _inputValidationRegex;
    private static object _lock = new object();

    // we make these public statics just so we can call them from externally for the
    // page method call
    public static XmlDocument Document
    {
        get
        {
            lock (_lock)
            {
                if (_document == null)
                {
                    // Read XML data from disk
                    _document = new XmlDocument();
                    _document.Load(HttpContext.Current.Server.MapPath("~/App_Data/CarsService.xml"));
                }
            }
            return _document;
        }
    }

    public static string[] Hierarchy
    {
        get { return new string[] { "make", "model" }; }
    }

    public static Regex InputValidationRegex
    {
        get
        {
            lock (_lock)
            {
                if (null == _inputValidationRegex)
                {
                    _inputValidationRegex = new Regex("^[0-9a-zA-Z \\(\\)]*$");
                }
            }
            return _inputValidationRegex;
        }
    }

    /// <summary>
    /// Helper web service method
    /// </summary>
    /// <param name="knownCategoryValues">private storage format string</param>
    /// <param name="category">category of DropDownList to populate</param>
    /// <returns>list of content items</returns>
    [WebMethod]
    public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContents(string knownCategoryValues, string category)
    {
        // Get a dictionary of known category/value pairs
        StringDictionary knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

        // Perform a simple query against the data document
        return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category, InputValidationRegex);
    }
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100