Search code examples
c#mysqlasp.netdrop-down-menuonselect

Change drop down list depending on selection C#


I have 2 drop down list ddlcountry and DdPetPist. ddlcountry has its own table in MYSQL database and so dose DdPetPist, I would like ddlcounty selection to change the table populating DdPetPist. so change the table from UK_Animals to France_Animals. or `Germany_Animals.

Code that populates drop down list

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                MySqlCommand cd2 = new MySqlCommand("SELECT * FROM Country", cs); // need to make it so changes database
                cs.Open();
                MySqlDataReader ddlCountry = cd2.ExecuteReader();
                ddlcountry.DataSource = ddlCountry;
                ddlcountry.DataValueField = "Country";
                ddlcountry.DataTextField = "Country";
                ddlcountry.DataBind();
                cs.Close();
                cs.Dispose();

                MySqlCommand cd = new MySqlCommand("SELECT * FROM UK_Animals", cs);
                cs.Open();
                MySqlDataReader ddlSpecie = cd.ExecuteReader();
                DdPetPist.DataSource = ddlSpecie;
                DdPetPist.DataValueField = "Specie";
                DdPetPist.DataTextField = "Specie";
                DdPetPist.DataBind();
                cs.Close();
                cs.Dispose();
            }

on select change for ddlcountry

 protected void ddlcountry_SelectedIndexChanged(object sender, EventArgs e)
    {

    }  

Would relay appreciate it if anyone could help.


Solution

  • Hope that I have understand correctly:

    protected void ddlcountry_SelectedIndexChanged(object sender, EventArgs e)
    {
      if(ddlcountry.Text!=string.Empty)
      {
          MySqlCommand cd = new MySqlCommand(string.Format("SELECT * FROM {0}_Animals",ddlcountry.Text), cs);
          cs.Open();
          MySqlDataReader ddlSpecie = cd.ExecuteReader();
          DdPetPist.DataSource = ddlSpecie;
          DdPetPist.DataValueField = "Specie";
          DdPetPist.DataTextField = "Specie";
          DdPetPist.DataBind();
          cs.Close();
          cs.Dispose();
      }
    }