Solved

Removing a listitem from a Databound ComboBox?

Posted on 2014-10-28
2
98 Views
Last Modified: 2016-02-18
I have 2 combobox controls on a windows form. They are both bound to a DataTable and contain Identical data. When a user selects the data, each selected item has to be different. I created a subroutine that would eliminate the selectedIndex in the second combobox but when it executed, it threw the followig exception:

 "Item collection cannot be modified when the DataSource property is set".

So, in order to make sure they can't select duplicate data, is there any way to remove an item from a ComboBox that is bound to a DataTable. The work-around is to simply display a message to the user indicating that they have made a duplicate selection but I would rather avoid that and address it in the ComboBoxes!

Thanks!
0
Comment
Question by:BlakeMcKenna
2 Comments
 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
ID: 40409056
You could accomplish this by using a Linq based query as your datasource (it's a little rough around the edges but I think you can get the gist of it), e.g.;
Form1.cs -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace ComboBoxExample
{
	public partial class Form1 : Form
	{
		private List<Food> foods = new List<Food>() 
		{
			new Food(0, "Select A Food", Type.None),
			new Food(1, "Corn", Type.Vegetable),
			new Food(2, "Apple", Type.Fruit),
			new Food(3, "Steak", Type.Meat),
			new Food(4, "Pea", Type.Vegetable),
			new Food(5, "Orange", Type.Fruit),
			new Food(6, "Ham", Type.Meat),
			new Food(7, "Potato", Type.Vegetable),
			new Food(8, "Rib", Type.Meat),
			new Food(9, "Banana", Type.Fruit),
			new Food(10, "Celery", Type.Vegetable)
		};

		public Form1()
		{
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			foodCombo1.DataSource = (from food in foods select food).ToList();
			foodCombo1.DisplayMember = "Name";
			foodCombo1.ValueMember = "ID";

			foodCombo2.Enabled = ((int)foodCombo1.SelectedIndex != -1 || (int)foodCombo1.SelectedValue != 0);
			foodCombo3.Enabled = ((int)foodCombo2.SelectedIndex != -1 || (int)foodCombo2.SelectedValue != 0);
		}

		private void OnSelectedIndexChanged(object sender, EventArgs e)
		{
			if (sender is ComboBox)
			{
				ComboBox cb = sender as ComboBox;
				if (cb == foodCombo1)
				{
					if ((int)foodCombo1.SelectedIndex != -1 || (int)foodCombo1.SelectedValue != 0)
					{
						foodCombo2.DataSource = (from food in foods where food.ID != (foodCombo1.SelectedItem as Food).ID && food.ID != 0 select food).ToList();
						foodCombo2.DisplayMember = "Name";
						foodCombo2.ValueMember = "ID";
						afterFoodSelect1.DataSource = foodCombo2.DataSource;
						afterFoodSelect1.DisplayMember = "Name";
						afterFoodSelect1.ValueMember = "ID";
						foodCombo2.Enabled = ((int)foodCombo1.SelectedIndex != -1 || (int)foodCombo1.SelectedValue != 0);
					}
				}

				if (cb == foodCombo2)
				{
					if ((int)foodCombo2.SelectedIndex != -1 || (int)foodCombo2.SelectedValue != 0)
					{
						foodCombo3.DataSource = (from food in foods where food.ID != (foodCombo1.SelectedItem as Food).ID && food.ID != (foodCombo2.SelectedItem as Food).ID && food.ID != 0 select food).ToList();
						foodCombo3.DisplayMember = "Name";
						foodCombo3.ValueMember = "ID";
						afterFoodSelect2.DataSource = foodCombo3.DataSource;
						afterFoodSelect2.DisplayMember = "Name";
						afterFoodSelect2.ValueMember = "ID";
						foodCombo3.Enabled = ((int)foodCombo2.SelectedIndex != -1 || (int)foodCombo2.SelectedValue != 0);
					}
				}

				if (cb == foodCombo3)
				{
					if ((int)foodCombo3.SelectedIndex != -1 || (int)foodCombo3.SelectedValue != 0)
					{
						afterFoodSelect3.DataSource = (from food in foods where food.ID != (foodCombo1.SelectedItem as Food).ID && food.ID != (foodCombo2.SelectedItem as Food).ID && food.ID != (foodCombo3.SelectedItem as Food).ID && food.ID != 0 select food).ToList();
						afterFoodSelect3.DisplayMember = "Name";
						afterFoodSelect3.ValueMember = "ID";
					}
				}
			}
		}
	}
}

Open in new window

Form1.Designer.cs -
namespace ComboBoxExample
{
	partial class Form1
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.label2 = new System.Windows.Forms.Label();
			this.foodCombo1 = new System.Windows.Forms.ComboBox();
			this.label3 = new System.Windows.Forms.Label();
			this.foodCombo2 = new System.Windows.Forms.ComboBox();
			this.label4 = new System.Windows.Forms.Label();
			this.foodCombo3 = new System.Windows.Forms.ComboBox();
			this.afterFoodSelect1 = new System.Windows.Forms.ListBox();
			this.afterFoodSelect2 = new System.Windows.Forms.ListBox();
			this.afterFoodSelect3 = new System.Windows.Forms.ListBox();
			this.SuspendLayout();
			// 
			// label2
			// 
			this.label2.AutoSize = true;
			this.label2.Location = new System.Drawing.Point(12, 9);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(75, 13);
			this.label2.TabIndex = 3;
			this.label2.Text = "Favorite Food:";
			// 
			// foodCombo1
			// 
			this.foodCombo1.FormattingEnabled = true;
			this.foodCombo1.Location = new System.Drawing.Point(12, 25);
			this.foodCombo1.Name = "foodCombo1";
			this.foodCombo1.Size = new System.Drawing.Size(121, 21);
			this.foodCombo1.TabIndex = 2;
			this.foodCombo1.SelectedIndexChanged += new System.EventHandler(this.OnSelectedIndexChanged);
			// 
			// label3
			// 
			this.label3.AutoSize = true;
			this.label3.Location = new System.Drawing.Point(139, 9);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(115, 13);
			this.label3.TabIndex = 5;
			this.label3.Text = "Second Favorite Food:";
			// 
			// foodCombo2
			// 
			this.foodCombo2.FormattingEnabled = true;
			this.foodCombo2.Location = new System.Drawing.Point(139, 25);
			this.foodCombo2.Name = "foodCombo2";
			this.foodCombo2.Size = new System.Drawing.Size(121, 21);
			this.foodCombo2.TabIndex = 4;
			this.foodCombo2.SelectedIndexChanged += new System.EventHandler(this.OnSelectedIndexChanged);
			// 
			// label4
			// 
			this.label4.AutoSize = true;
			this.label4.Location = new System.Drawing.Point(266, 9);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(104, 13);
			this.label4.TabIndex = 7;
			this.label4.Text = "Least Favorite Food:";
			// 
			// foodCombo3
			// 
			this.foodCombo3.FormattingEnabled = true;
			this.foodCombo3.Location = new System.Drawing.Point(266, 25);
			this.foodCombo3.Name = "foodCombo3";
			this.foodCombo3.Size = new System.Drawing.Size(121, 21);
			this.foodCombo3.TabIndex = 6;
			this.foodCombo3.SelectedIndexChanged += new System.EventHandler(this.OnSelectedIndexChanged);
			// 
			// afterFoodSelect1
			// 
			this.afterFoodSelect1.FormattingEnabled = true;
			this.afterFoodSelect1.Location = new System.Drawing.Point(12, 52);
			this.afterFoodSelect1.Name = "afterFoodSelect1";
			this.afterFoodSelect1.Size = new System.Drawing.Size(120, 199);
			this.afterFoodSelect1.TabIndex = 8;
			// 
			// afterFoodSelect2
			// 
			this.afterFoodSelect2.FormattingEnabled = true;
			this.afterFoodSelect2.Location = new System.Drawing.Point(139, 52);
			this.afterFoodSelect2.Name = "afterFoodSelect2";
			this.afterFoodSelect2.Size = new System.Drawing.Size(120, 199);
			this.afterFoodSelect2.TabIndex = 9;
			// 
			// afterFoodSelect3
			// 
			this.afterFoodSelect3.FormattingEnabled = true;
			this.afterFoodSelect3.Location = new System.Drawing.Point(267, 52);
			this.afterFoodSelect3.Name = "afterFoodSelect3";
			this.afterFoodSelect3.Size = new System.Drawing.Size(120, 199);
			this.afterFoodSelect3.TabIndex = 10;
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(588, 262);
			this.Controls.Add(this.afterFoodSelect3);
			this.Controls.Add(this.afterFoodSelect2);
			this.Controls.Add(this.afterFoodSelect1);
			this.Controls.Add(this.label4);
			this.Controls.Add(this.foodCombo3);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.foodCombo2);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.foodCombo1);
			this.Name = "Form1";
			this.Text = "Form1";
			this.Load += new System.EventHandler(this.Form1_Load);
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.ComboBox foodCombo1;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.ComboBox foodCombo2;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.ComboBox foodCombo3;
		private System.Windows.Forms.ListBox afterFoodSelect1;
		private System.Windows.Forms.ListBox afterFoodSelect2;
		private System.Windows.Forms.ListBox afterFoodSelect3;
	}
}

Open in new window

Food and supporting classes -
using System;
using System.Collections.Generic;

namespace ComboBoxExample
{
	/// <summary>Class Food.</summary>
	public class Food
	{
		private int fId = -1;
		private string fName = string.Empty;
		private Type fType = Type.None;

		/// <summary>Gets or sets the identifier.</summary>
		/// <value>The identifier.</value>
		public int ID
		{
			get { return fId; }
			set
			{
				if (!value.Equals(fId))
					fId = value;
			}
		}

		/// <summary>Gets or sets the name.</summary>
		/// <value>The name.</value>
		public string Name
		{
			get { return fName; }
			set
			{
				if (!value.Equals(fName))
					fName = value;
			}
		}

		/// <summary>Gets or sets the type.</summary>
		/// <value>The type.</value>
		public Type Type
		{
			get { return fType; }
			set
			{
				if (!value.Equals(fType))
					fType = value;
			}
		}

		/// <summary>Prevents a default instance of the <see cref="Food"/> class from being created.</summary>
		private Food() { ;}

		/// <summary>Initializes a new instance of the <see cref="Food"/> class.</summary>
		/// <param name="ID">The identifier.</param>
		/// <param name="Name">The name.</param>
		/// <param name="Type">The type.</param>
		public Food(int ID, string Name, Type Type)
		{
			this.ID = ID;
			this.Name = Name;
			this.Type = Type;
		}
	}

	public enum @Type : int
	{
		None = 0,
		Fruit = 1,
		Vegetable = 2,
		Meat = 3
	}
}

Open in new window

Produces the following output:Capture.JPG
-saige-
0
 

Author Closing Comment

by:BlakeMcKenna
ID: 40409540
Thanks, but I just used the message route instead. It's not how I really wanted to do it but it's much simpler!
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now