locked
2 dropdownlists in webform RRS feed

  • Question

  • User156871696 posted

    Hello, am learning asp.net . İ am making dropdownlist , i like to explain my problem via a sample. İ have two dropdownlist ,dropdownlist1 and dropdownlist2 , i am choosing Turkey from dropdownlist1 ,Ankara from dropdownlist2 , when i reload page values are changing. Thank you for your helping

    Friday, February 22, 2019 11:06 PM

All replies

  • User409696431 posted

    Please provide more information.  How are you providing the values for the dropdowns?  When are you providing them?  What are the values changing to after postback?

    Saturday, February 23, 2019 1:51 AM
  • User156871696 posted
    Hello,

    1-) i have acces database , there are two table cities and town , i am pulling data to dropdownlist from my database
    2-) when i open my web page , i am seeking my city via dropdownlist1 , town dropdownlist2
    3-) after postback nothing change , everything is ok

    My problem is this,

    when i open page everytime. i want to see same places.
    Changing places when i close the webpage and then reopen it again

    Thank you very much for your help

    Regards
    Saturday, February 23, 2019 10:55 AM
  • User409696431 posted

    It is not typical behavior for controls to have the same value as the last time you opened the page.  In order to see the same value when you open the page again at a later time, you have to store the values somewhere, look for that value on pageload, and set the dropdowns to those values after you databind them. Are the values you want to save going to be associated with each visitor to the site?  If so, you have to have a way of identifying the visitor and storing the value in a way that associates it with the visitor.

    As an example, if this is a site with membership, you could use a table in the database that associates the values with the member id.

    Saturday, February 23, 2019 2:57 PM
  • User839733648 posted

    Hi AhmetOzer,

    According to your description, I suggest that you could use database to do this.

    Page will refresh to default when you reload it.

    So when you selecting the item, then save the result to database.

    And when you open the page again, you could let it read the data saving last time.

    Best Regards,

    Jenifer

    Monday, February 25, 2019 7:44 AM
  • User156871696 posted
    Dear Jenifer,

    Thank you very much for information, can you please provide
    a simple sample , if this don’t take much time.
    Because i tried this way , i couldn’t do it.

    This is my code



    protected void save_Click(object sender, EventArgs e) *** this button for saving *****
    {
    OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/App_Data/cities.accdb") + ";Persist
    Security Info=True");
    conn.Open();

    string id = DropDownList1.SelectedValue; ****(note : this id for selected city)****
    string town = DropDownList2.SelectedItem.Text;


    string connstr = "INSERT INTO selectedcitytown (id,town) VALUES (''" + @id + "',''" + @town + "')";
    OleDbCommand com = new OleDbCommand(connstr, conn);
    com.Parameters.AddWithValue("@id", DropDownList1.SelectedValue);
    com.Parameters.AddWithValue("@town", DropDownList2.SelectedItem.Text);
    com.ExecuteNonQuery();
    Response.Redirect("~/PURSAKLAR/TumHaritaIlanlari.aspx");
    }


    database :name cities
    inside database :there are 3 tables
    table 1: cities ( id ,city) / (numeric, text) ****note for DropDownList1 ****
    table2: towns (id, town, city)/( numeric,text,numeric) ***note for DropDownList2 ****
    table3: selectedcitytown (city,town)/(text,text)
    Monday, February 25, 2019 8:38 AM
  • User409696431 posted

    Ahmet,Ozer,

    The code you show is only for saving the values to the database (does that part work?).  It does not populate the dropdowns with those values the next time you come to the page, and it has no way to tell who the visitor is.   Unless you want the dropdowns to be set to the values the last visitor set, not the values each visitor set the last time they were at that page, you have to store different values for each visitor.   The first thing you have to decide is: How will you identify that a returning visitor has been to the site before and has saved values?   That's why I mentioned membership in my earlier reply, and as a way (not the only way) to do this.

    Monday, February 25, 2019 2:37 PM
  • User156871696 posted

    Dear Kathy,

    You are right reallly , now i understood . This way is not a way to solve my problem.

    Thank you so much

    Best Regards

    Ahmet

    Monday, February 25, 2019 5:03 PM
  • User839733648 posted

    Hi AhmetOzer,

    I have another better suggestion that you could use session to store the selected item and read it when reloading.

    Here is my demo.

    .aspx

                <asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"  AutoPostBack="true" OnDataBound="DropDownList1_DataBound" >
                </asp:DropDownList>

    code-behind.

            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindData();
                }
            }
            string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            private void BindData()
            {
                SqlConnection con = new SqlConnection(constr);
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select Eid,Ename from tb_info";
                SqlDataAdapter adp = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adp.Fill(ds, "tb_info");
                DropDownList1.DataSource = ds;
                DropDownList1.DataTextField = "Ename";
                DropDownList1.DataValueField = "Eid";
                DropDownList1.DataBind();
    
            }
    
            protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
            {//save to session
                Session["dd1"] = DropDownList1.SelectedValue;
            }
    
            protected void DropDownList1_DataBound(object sender, EventArgs e)
            {//read session
                DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(Convert.ToString(Session["dd1"])));
            }

    result:

    Best Regards,

    Jenifer

    Tuesday, February 26, 2019 10:01 AM
  • User-2054057000 posted

    This situation arises when you bind the drop down in code behind by not using !postback. The correct solution is:

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
           // Bind your drop downs
        }
    }

    Tuesday, February 26, 2019 11:28 AM
  • User156871696 posted

    Dear Jenifer ,

    Thank you so much , i will check and back to you to give information.

    Hava good day.

    Regards

    Ahmet

    Tuesday, February 26, 2019 12:04 PM
  • User156871696 posted

    Thank you.

    Regards

    Ahmet

    Tuesday, February 26, 2019 12:05 PM
  • User156871696 posted

    Dear Jenifer ,

    I have tried and tested below codes , codes are giving some mistake as you see below.

    Thank you so much for your helping

    Have good day

    Ahmet OZER

    TEST RESULT AND ERRORS

    ******************************************************************************************************************************************************
    Server Error in '/sil8' Application.
    Object reference not set to an instance of an object.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

    Source Error:


    Line 27: }
    Line 28: }
    Line 29: string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    Line 30: private void BindData()
    Line 31: {

    Source File: c:\Users\OZER\Desktop\sil test sil\sil dropdown test\sil8\PURSAKLAR\TumHaritaIlanlari.aspx.cs Line: 29

    Stack Trace:


    [NullReferenceException: Object reference not set to an instance of an object.]
    Default..ctor() in c:\Users\OZER\Desktop\sil test sil\sil dropdown test\sil8\PURSAKLAR\TumHaritaIlanlari.aspx.cs:29
    ASP.pursaklar_tumharitailanlari_aspx..ctor() in c:\Users\OZER\AppData\Local\Temp\Temporary ASP.NET Files\sil8\e0cec965\b312c8e0\App_Web_f1j0j10q.0.cs:0
    __ASP.FastObjectFactory_app_web_f1j0j10q.Create_ASP_pursaklar_tumharitailanlari_aspx() in c:\Users\OZER\AppData\Local\Temp\Temporary ASP.NET Files\sil8\e0cec965\b312c8e0\App_Web_f1j0j10q.2.cs:0
    System.Web.Compilation.BuildResultCompiledType.CreateInstance() +31
    System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp) +100
    System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +31
    System.Web.UI.PageHandlerFactory.System.Web.IHttpHandlerFactory2.GetHandler(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +64
    System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +191
    System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +145
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155


    ******************************************************************************************************************************************************

    WEB SITE CODES
    ***************


    .aspx
    *******************************************************************************************************************************************************

    <asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true" OnDataBound="DropDownList1_DataBound" >
    </asp:DropDownList>

    .aspx.cs
    ********************************************************************************************************************************************************

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    BindData();
    }
    }
    string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    private void BindData()
    {
    OleDbConnection con = new OleDbConnection(constr);
    con.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select id,city from cities";
    OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
    DataSet ds = new DataSet();
    adp.Fill(ds, "cities");
    DropDownList1.DataSource = ds;
    DropDownList1.DataTextField = "city";
    DropDownList1.DataValueField = "id";
    DropDownList1.DataBind();

    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {//save to session
    Session["dd1"] = DropDownList1.SelectedValue;
    }

    protected void DropDownList1_DataBound(object sender, EventArgs e)
    {//read session
    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(Convert.ToString(Session["dd1"])));
    }

    ********************************************************************************************************************************************************
    database name : cities
    inside database :there are 3 tables
    table 1: cities ( id ,city) / (numeric, text) ****note for DropDownList1 ****
    table2: towns (id, town, city)/( numeric,text,numeric) ***note for DropDownList2 ****
    table3: selectedcitytown (city,town)/(text,text)

    Wednesday, February 27, 2019 11:01 AM
  • User839733648 posted

    Hi AhmetOzer,

    Line 29: string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

    You could see from the error message that the ConnectionString you've used is wrong so you could not get the data succesdfully.

    This string is related to the name of connectionStrings in your Web.config file.

    Here is my Web.config file. Pay attention to the highlight content.

    <?xml version="1.0"?>
    <configuration>
      <connectionStrings>
        <add name="EmployeeManagementConnectionString" connectionString="Data Source=(localdb)\mssqllocaldb;Initial Catalog=EmployeeManagement;Integrated Security=True" providerName="System.Data.SqlClient"/>
      </connectionStrings>
    ...
    </configuration>

    So my constr is written like:

    string constr = ConfigurationManager.ConnectionStrings["EmployeeManagementConnectionString"].ConnectionString;

    I suggest that you could check your Web.config file.

    Best Regards,

    Jenifer

    Thursday, February 28, 2019 2:35 AM
  • User409696431 posted

    Amet,

    Are you trying to store values when people go back to the site later?  Or just when they are staying on your site during one visit?  Session will not work in the first case.  If you make your requirement clear it would help.

    Friday, March 1, 2019 4:22 AM
  • User156871696 posted

    Dear Jenifer

    I have checked  my Web.config as you said  , i have compared your code and my code , and finally i did.

    Of course  my influence on this work  may be %10 , actually you solved this problem.

    Thank you

    Ahmet OZER

    Saturday, March 2, 2019 11:20 AM
  • User156871696 posted

    Dear Kathy,

    Thank you very much for your interesting , my respond is as below,

    Are you trying to store values when people go back to the site later? ****(My answer is no)***** Or just when they are staying on your site during one visit?**(my answer is yes)****  Session will not work in the first case.  If you make your requirement clear it would help.

    Thank you very much

    Have good day

    Regards

    Ahmet

    Saturday, March 2, 2019 11:25 AM
  • User156871696 posted

    Dear Jenifer ,

    I want to thank you very much again.

    Have a good day

    Ahmet

    Saturday, March 2, 2019 11:29 AM
  • User156871696 posted
    Dear jenifer ,

    I am trying to make to dropdownlist (dropdownlist1 and dropdownlist2 ) as follow. First dropdownlist is ok (dropdownlist1)

    But secon dropdownlist (dropdownlist2) is not showing list of towns

    Have a good day

    Ahmet

    ******** .aspx.cs ****

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Data.OleDb;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;

    public partial class Default : System.Web.UI.Page
    {

    string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Bolgeler.accdb;Persist Security Info=True";


    public void Bind_DropDownList1()
    {
    OleDbConnection con = new OleDbConnection(constr);
    con.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select CityNo,City from Cities";
    OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
    DataSet ds = new DataSet();
    adp.Fill(ds, "Cities");
    DropDownList1.DataSource = ds;
    DropDownList1.DataTextField = "City";
    DropDownList1.DataValueField = "CityNo";
    DropDownList1.DataBind();

    }




    public void Bind_DropDownList2()
    {
    OleDbConnection con = new OleDbConnection(constr);
    con.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select TownNo,Town from Towns where CityNo='" + DropDownList1.SelectedValue + "';
    OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
    DataSet ds = new DataSet();
    adp.Fill(ds, "Towns");
    DropDownList2.DataSource = ds;
    DropDownList2.DataTextField = "Town";
    DropDownList2.DataValueField = "TownNo";
    DropDownList2.DataBind();

    }

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    Bind_DropDownList1();
    }
    }


    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {//save to session
    Session["dd1"] = DropDownList1.SelectedValue;
    }

    protected void DropDownList1_DataBound(object sender, EventArgs e)
    {//read session
    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(Convert.ToString(Session["dd1"])));
    }


    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {//save to session
    Session["dd2"] = DropDownList2.SelectedValue;
    }

    protected void DropDownList2_DataBound(object sender, EventArgs e)
    {//read session
    DropDownList2.SelectedIndex = DropDownList2.Items.IndexOf(DropDownList2.Items.FindByValue(Convert.ToString(Session["dd2"])));
    }

    *** .aspx *******

    <asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true" OnDataBound="DropDownList1_DataBound" >
    </asp:DropDownList>


    <asp:DropDownList ID="DropDownList2" AppendDataBoundItems="true" runat="server" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" AutoPostBack="true" OnDataBound="DropDownList2_DataBound" >
    </asp:DropDownList>
    Saturday, March 2, 2019 12:51 PM
  • User839733648 posted

    Hi AhmetOzer,

    According to your description, it seems that you did not callback the Bind_DropDownList2() event.

    protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    Bind_DropDownList1();
                }
    
            }
    
            string constr = ConfigurationManager.ConnectionStrings["EmployeeManagementConnectionString"].ConnectionString;
            private void Bind_DropDownList1()
            {
                SqlConnection con = new SqlConnection(constr);
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select * from tb_Province";
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                sda.Fill(ds, "tb_Province");
                DropDownList1.DataSource = ds;
                DropDownList1.DataTextField = "proName";
                DropDownList1.DataValueField = "proID";
                DropDownList1.DataBind();
    
            }
    
            private void Bind_DropDownList2()
            {
                SqlConnection con = new SqlConnection(constr);
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select * from tb_City where proID=" + DropDownList1.SelectedValue.ToString();
                SqlDataAdapter adp = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adp.Fill(ds, "tb_City");
                DropDownList2.DataSource = ds;
                DropDownList2.DataTextField = "cityName";
                DropDownList2.DataValueField = "cityID";
                DropDownList2.DataBind();
    
            }
            protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
            {
                DropDownList2.Items.Clear();
                Bind_DropDownList2();
                Session["dd1"] = DropDownList1.SelectedValue;
            }
    
            protected void DropDownList1_DataBound(object sender, EventArgs e)
            {
                DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(Convert.ToString(Session["dd1"])));
            }
    
            protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
            {
                Session["dd2"] = DropDownList2.SelectedValue;
            }
    
            protected void DropDownList2_DataBound(object sender, EventArgs e)
            {
                DropDownList2.SelectedIndex = DropDownList2.Items.IndexOf(DropDownList2.Items.FindByValue(Convert.ToString(Session["dd2"])));
            }

    result:

    Best Regards,

    Jenifer

    Monday, March 4, 2019 8:52 AM
  • User156871696 posted

    Dear Jenifer,

    Thank you very much for your respond ,

    First  and second step is ok, i need finalize final step i mean third step.

    dropdownlist1  listing is ok and also cities not changing this is also ok.

    dropdownlist2 listing is ok  , this is good.  But when i refresh the page towns are  changing , but i dont want it changed when i refresh page.

    Best Regards

    .aspx ****

    <asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" OnDataBound="DropDownList1_DataBound" AutoPostBack="True" >
    </asp:DropDownList>

    <asp:DropDownList ID="DropDownList2" AppendDataBoundItems="true" runat="server" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" AutoPostBack="true" OnDataBound="DropDownList2_DataBound" >
    </asp:DropDownList>

    aspx.cs ****

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Data.OleDb;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;

    public partial class Default : System.Web.UI.Page
    {

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    Bind_DropDownList1();
    }

    }

    string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\CitiesTowns.accdb;Persist Security Info=True";
    private void Bind_DropDownList1()
    {
    OleDbConnection con = new OleDbConnection(constr);
    con.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select * from Cities";
    OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
    DataSet ds = new DataSet();
    sda.Fill(ds, "Cities");
    DropDownList1.DataSource = ds;
    DropDownList1.DataTextField = "City";
    DropDownList1.DataValueField = "CityId";
    DropDownList1.DataBind();

    }

    private void Bind_DropDownList2()
    {
    OleDbConnection con = new OleDbConnection(constr);
    con.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select * from Towns where CityId=" + DropDownList1.SelectedValue.ToString();
    OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
    DataSet ds = new DataSet();
    adp.Fill(ds, "Towns");
    DropDownList2.DataSource = ds;
    DropDownList2.DataTextField = "Town";
    DropDownList2.DataValueField = "TownId";
    DropDownList2.DataBind();

    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {

    DropDownList2.Items.Clear();
    Bind_DropDownList2();
    Session["dd1"] = DropDownList1.SelectedValue;
    }

    protected void DropDownList1_DataBound(object sender, EventArgs e)
    {
    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(Convert.ToString(Session["dd1"])));
    }

    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
    Session["dd2"] = DropDownList2.SelectedValue;
    }

    protected void DropDownList2_DataBound(object sender, EventArgs e)
    {
    DropDownList2.SelectedIndex = DropDownList2.Items.IndexOf(DropDownList2.Items.FindByValue(Convert.ToString(Session["dd2"])));
    }

    Monday, March 4, 2019 7:58 PM
  • User839733648 posted

    Hi AhmetOzer,

    I suggest you just need to add Bind_DropDownList2() to !IsPostBack condition.

                if (!IsPostBack)
                {
                    Bind_DropDownList1();
                    Bind_DropDownList2();
                }

    result:

    Best Regards,

    Jenifer

    Tuesday, March 5, 2019 2:40 AM
  • User156871696 posted

    Dear Jenifer,

    Thank you. 

    Super,  codes are working as i wanted, and i learned this subject very well.

    Thank you very much again , because I asked you many questions and you have always answered to my questions.

    Thank you very much again

    Have a good day

    Ahmet OZER

    aspx.cs *****

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Data.OleDb;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;

    public partial class Default : System.Web.UI.Page
    {

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    Bind_DropDownList1();
    Bind_DropDownList2();
    }

    }

    string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\CitiesTowns.accdb;Persist Security Info=True";
    private void Bind_DropDownList1()
    {
    OleDbConnection con = new OleDbConnection(constr);
    con.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select * from Cities";
    OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
    DataSet ds = new DataSet();
    sda.Fill(ds, "Cities");
    DropDownList1.DataSource = ds;
    DropDownList1.DataTextField = "City";
    DropDownList1.DataValueField = "CityId";
    DropDownList1.DataBind();

    }

    private void Bind_DropDownList2()
    {
    OleDbConnection con = new OleDbConnection(constr);
    con.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select * from Towns where CityId=" + DropDownList1.SelectedValue.ToString();
    OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
    DataSet ds = new DataSet();
    adp.Fill(ds, "Towns");
    DropDownList2.DataSource = ds;
    DropDownList2.DataTextField = "Town";
    DropDownList2.DataValueField = "TownId";
    DropDownList2.DataBind();

    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {

    DropDownList2.Items.Clear();
    Bind_DropDownList2();
    Session["dd1"] = DropDownList1.SelectedValue;
    }

    protected void DropDownList1_DataBound(object sender, EventArgs e)
    {
    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(Convert.ToString(Session["dd1"])));
    }

    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
    Session["dd2"] = DropDownList2.SelectedValue;
    }

    protected void DropDownList2_DataBound(object sender, EventArgs e)
    {
    DropDownList2.SelectedIndex = DropDownList2.Items.IndexOf(DropDownList2.Items.FindByValue(Convert.ToString(Session["dd2"])));
    }

    }

    aspx  ****

    <asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" OnDataBound="DropDownList1_DataBound" AutoPostBack="True" >
    </asp:DropDownList>

    <asp:DropDownList ID="DropDownList2" AppendDataBoundItems="true" runat="server" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" AutoPostBack="true" OnDataBound="DropDownList2_DataBound" >
    </asp:DropDownList>

    Tuesday, March 5, 2019 10:10 AM