How to Pass ComboBox items as Cnstructor Parameter
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: How to Pass ComboBox items as Cnstructor Parameter

  1. #1
    Join Date
    Jun 2010
    Posts
    15

    Smile How to Pass ComboBox items as Cnstructor Parameter

    Hi
    Could you please let me know how I can pass a combobox items as constructor parameter?
    As you can see from the codes I have a combobox which is loaded by enum FilmType.now I want to create a movie object by constructor Movie() like:
    Movie film = new Movie(textBox1.Text, comboBox1.SelectedItem.ToString());
    but I can not convert the item type to enum type!
    I Have following Classes:

    //======================================= Movie.cs
    public class Movie
    {
    public enum FilmType
    {
    Action,
    Comedy,
    Horor,
    }
    private string title;
    private FilmType type;

    public Movie(string title, FilmType type)
    {
    this.title = title;
    this.type = type;
    }
    public Movie() { }

    public string Title
    {
    get { return title; }
    set { this.title = value; }
    }
    public FilmType MovieType
    {
    get { return type; }
    set { this.type = value; }
    }
    public override string ToString()
    {
    return Title;
    }
    }
    and I have a Form application as below:
    //================================== Form1.cs
    public partial class Form1 : Form
    {

    public Form1()
    {
    InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
    Movie film = new Movie(textBox1.Text, comboBox1.SelectedItem.ToString());
    istBox3.Items.Add(film);
    textBox1.Clear();
    textBox1.Select();
    comboBox1.SelectedIndex = -1;

    }

    private void Form1_Load(object sender, EventArgs e)
    {
    {
    foreach (string movieType in Enum.GetNames(typeof(Movie.FilmType)))
    {
    comboBox1.Items.Add(movieType);
    }
    }
    }
    }
    //========================================================

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: How to Pass ComboBox items as Cnstructor Parameter

    I noticed this problem in your last topic and you are just going about it the wrong way. You store objects in ComboBoxes. Those objects do not need to be strings (though they will be displayed using the ToString( ) method), so instead of adding raw strings just add the enum values themselves.

    If for some reason you are determined to do it this way, just use this:

    Code:
    Enum.Parse( typeof( MyEnum ), comboBox1.SelectedValue.ToString( ) );

  3. #3
    Join Date
    Jun 2010
    Posts
    15

    Re: How to Pass ComboBox items as Cnstructor Parameter

    Hi BigEd781,
    Thanks for ur comment but to be honest I got more confused!
    lets make it simple! could you please tell me how I can create a new object by using an enum and combobox in form application?
    is there any problem in combobox loading part?
    foreach (string movieType in Enum.GetNames(typeof(Movie.FilmType)))
    {
    comboBox1.Items.Add(movieType);
    }

    if not how I can use this item as my Movie constructor?
    Thanks again

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    11,357

    Re: How to Pass ComboBox items as Cnstructor Parameter

    When I replied to the previous post, I gave the quick and dirty answer.

    Although you can add an enum directly to the combobox, in practice you probably don't want to do this. Sure it works okay for simple programs, but professional programs usually don't have single word descriptions for a enum type.

    Most beginning programers don't understand that many control items have a DataSource property which can be used to bind to a collection.

    So rather than simply adding the items to the combobox manually like I showed in your previous post, you create a collection of items and bind to them with the datasource.

    The benefits may not be apparent in this simple example, but when you take this approach, the SelectedItem becomes an instance of the selected object in the list. This means, you can access any property of that item.

    Here's the code (see the attached project for the complete solution):

    Code:
    namespace CG.ComboBox
    {
        #region Using Directives
    
        using System;
        using System.Collections.Generic;
        using System.Windows.Forms;
    
        #endregion Using Directives
    
        internal enum Genre
        {
            Action,
            Comedy,
            Horror,
            Chick
        };
    
        public partial class Form1 : Form
        {
            public Form1( )
            {
                InitializeComponent( );
            }
    
            private void btnFill_Click( object sender, EventArgs e )
            {
                _filmTypeList.Clear( );
    
                _filmTypeList.Add( FilmType.Create( "Films that make your heart race.", Genre.Action ) );
                _filmTypeList.Add( FilmType.Create( "Films that make you laugh.", Genre.Comedy ) );
                _filmTypeList.Add( FilmType.Create( "Films that scare you.", Genre.Horror ) );
    
                // (re) Bind the combobox to the generic list
                comboBoxFilmType.DataSource = null; // force a rebind
                comboBoxFilmType.DataSource = _filmTypeList;
    
                // As an alternate to overriding FilmType.ToString( ), the DisplayMember
                // can be used to specify the FilmType property used in the combobox's display.
                // comboBoxFilmType.DisplayMember = "Display";
    
    
                // Enable the Add One button
                btnAddOne.Enabled = true;
            }
    
            private void btnGetFilmType_Click( object sender, EventArgs e )
            {
                if( comboBoxFilmType.SelectedItem == null ) return;
    
                var selectedFilmType = comboBoxFilmType.SelectedItem as FilmType;
    
                if ( selectedFilmType == null ) return;
    
                MessageBox.Show(String.Format( "You selected: {0}", selectedFilmType.Genre ), "Genre" );
            }
    
            private readonly List< FilmType > _filmTypeList = new List<FilmType>( );
    
            private void btnAddOne_Click( object sender, EventArgs e )
            {
                // Add an extra entry
                _filmTypeList.Add( FilmType.Create( "Films that bore men.", Genre.Chick ) );
    
                // (re) Bind the combobox to the generic list
                comboBoxFilmType.DataSource = null; // force a rebind
                comboBoxFilmType.DataSource = _filmTypeList;
    
                // Disable the add one button (to avoid duplicate chick entries)
                btnAddOne.Enabled = false;
            }
        }
    
        internal class FilmType
        {
            public static FilmType Create( string display, Genre genre )
            {
                return new FilmType
                {
                    Display = display
                     ,
                    Genre = genre
                };
            }
    
            public Genre Genre { get; private set; }
            public string Display { get; private set; }
    
            // Override the ToString member - when the combobox.DisplayMember is not
            // set, ComboBox uses the ToString as the display for the comboBox
            public override string ToString( )
            {
                return Display;
            }
        }
    }
    In this snippet, I've create an enum type of Genre (Action, Comedy, Horror, Chick). I've also created a FilmType class that stores the Genre and a string Display. The display property allows us to display something different than just the text of the enum. It may not matter at this stage of the program, but in the future, you make want to localize the application, so understanding this capability may be important down the road.

    This sample also creates a generic list of the FilmType class and this list is bound to the Combobox using the DataSource property. The advantage here is that items can be added and removed from the list and the changes will be reflected in the combobox. As mentioned earlier, it simplifies the code because the selected item is actually the real object so you have access to the selected item's properties. Not too impressive in this case, but imagine binding to a list of employee objects. The combobox may show something like "Arjay from CodeGuru", but the selecteditem object allows me direct access to the employee id, the age, firstname, lastname, etc. It's a powerful technique (and one that becomes even more powerful in WPF).
    Attached Files Attached Files

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center