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);
}
}
}
}
//========================================================
Loading
Bruce RoeserPosted Jul 7, 2010, 11:31 AM
--- Form Code ---
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace LangTest {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
comboBox1.Items.Add("Action");
comboBox1.Items.Add("Comedy");
comboBox1.Items.Add("Horror");
}
private void button1_Click(object sender, EventArgs e) {
Movie film = new Movie(textBox1.Text, (Movie.FilmType) comboBox1.SelectedIndex);
listBox1.Items.Add(film);
textBox1.Clear();
textBox1.Select();
comboBox1.SelectedIndex = -1;
}
}
}
---
You are simply trying to pass a string to the constructor when the enum value is called for. Notice that in the form I populate the combo box in the same order as the enum you have set up - so the index values should correspond exactly to the enum values. In the constructor I simply pass the selected index of the combo but, of course, have to coerce it to the FilmType enum. If you set a breakpoint in the constructor you will see that the correct enum value is passed and stored.
-b