Masriyah
Masriyah

Reputation: 2505

Dynamically update combobox based on user selection

I am not sure how postback works on WinForms, but I want to allow the ComboBox to update based on the user selection.

Currently when I change the selection of my first ComboBox, it doesn't change the items in the second dropdown. (only showing the first item by default)

In what ways can O alter this?

Code to what I have:

public ContentUploader()
{
    InitializeComponent();
    using (SqlConnection con = new SqlConnection(conString))
    {
        con.Open();
        using (SqlDataAdapter sda = new SqlDataAdapter("SELECT ... re.OverallID = 1", conString))
        {
            DataTable dt = new DataTable();
            sda.Fill(dt);
            sections_drp.ValueMember = "ID";
            sections_drp.DisplayMember = "DisplayName";
            sections_drp.DataSource = dt;
        }
    }
    sections_drp.SelectedIndexChanged += (o, e) => FillFirstChildren();
}
public void FillFirstChildren()
{
    firstChild_drp.Items.Add("Select Item");
    firstChild_drp.SelectedIndex = 0;
    string sectionId = sections_drp.SelectedValue.ToString();
    using (SqlConnection con = new SqlConnection(conString))
    {
        con.Open();
        using (SqlDataAdapter sda = new SqlDataAdapter("SELECT ... em.ItemID = ("+ sectionId +")", conString))
        {
            DataTable dt = new DataTable();
            sda.Fill(dt);
            firstChild_drp.ValueMember = "ID";
            firstChild_drp.DisplayMember = "DisplayName";
            firstChild_drp.DataSource = dt;
        }
    }
    FillSecondChildren();
}

Upvotes: 1

Views: 937

Answers (1)

Khan
Khan

Reputation: 18162

Winforms does not contain a post back. You will need to tie to the SelectedIndexChanged (or Item or Value) event to filter your second dropdown.

Example:

    public void FillFirstChildren()
    {
        //Your Fill Logic Here
        ...

        //Call FillSecondChildren on selection change
        firstChild_drop.SelectedIndexChanged += (o, e) => FillSecondChildren();
    }

Upvotes: 2

Related Questions