Search code examples
c#wpfcomboboxtextbox

WPF fill in textbox based on selected item combobox


I've made a WPF project about movies and actors (new to programming).

For now I can create a new actor (linked to a movie) manually by entering his name, country, bday etc. Since I'm adding more and more data, I would like the possibility to select an existing actor from a combobox, and then his name, country, bday etc would automatically fill in in the textboxes I've provided where you'd normally add new information manually.

My Actor has an ActorID, FirstName, LastName, Country and Birthdate. If I want to create a new actor, I just fill these things in and click save, and it creates a new actor. The save thing is not really important right now.

In Actor.cs I declared these:

public class Actor
{
    public int ActorID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    //Etc.
}

And then these are called act.FirstName etc

My combobox is called: comboBoxExistingActors and it's Itemsource is:

        comboBoxExistingActors.ItemsSource = ActorRepository.ActorList();

This ActorList is defined in my ActorRepository:

    public static List<Actor> ActorList()
    {
        string command = "SELECT DISTINCT FirstName, LastName FROM tblActors ORDER BY tblActors.LastName";
        OleDbDataAdapter adapter = new OleDbDataAdapter(command, connectionString);
        DataTable datatable = new DataTable();
        adapter.Fill(datatable);

        List<Actor> lijst = new List<Actor>();

        for (int i = 0; i < datatable.Rows.Count; i++)
        {
            Actor act = new Actor();

            act.FirstName = datatable.Rows[i].Field<string>("FirstName");
            act.LastName = datatable.Rows[i].Field<string>("LastName");

            lijst.Add(act);
        }
        return lijst;
    }

Now I'd like that my textboxes would fill in the actor's details when I select an actor from this combobox:

    private void comboBoxExistingActors_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        textBoxFirstName.Text = ???
        //textBoxLastname etc.
    }

I'm not sure if it's this simple, but I need a way to get my act.Firstname from the selected actor into the textBoxFirstName. I hope I have provided enough information to understand my problem, if not please say so and I'll provide you with it.

Thanks in advance!


Solution

  • I think you are looking for something like this:

    private void comboBoxExistingActors_SelectionChanged(object sender, SelectionChangedEventArgs e)
     {
        textBoxFirstName.Text = ((Actor)comboBoxExistingActors.SelectedItem).FirstName;
     }