Solved

Using AddRange to populate comboBox with data stored in a Dictionary

Posted on 2016-09-13
7
48 Views
Last Modified: 2016-09-13
Good morning experts,

This is my first time trying to use the comboBox AddRange method in C#.
I have data retrieved from a table in SqlServer database and placed in Dictionary, the key is of integer type and the value is of type string.
Next comes the problem of placing the pair (key and value) int a comboBox. I tried several things but none worked.
Below is the code which is placed on the Form_Load event where the comboBox reside:

  private void FrmADDNewCleaningJob_Load(object sender, EventArgs e)
        {
            RetrieveAllUnits getUnits = default(RetrieveAllUnits);
            getUnits = new RetrieveAllUnits();
            getUnits.FillUnitaList();
            if (getUnits.Dict.Count > 0)
                foreach (var pair in getUnits.Dict)
                {
                  // code to fill the comboBox
                }
            else
            {
                MessageBox.Show("We have a problem!");
            }
0
Comment
Question by:Adam Trask
  • 5
7 Comments
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 41796146
>>This is my first time trying to use the comboBox AddRange method in C#.

Your code snippet doesn't use that anywhere.
0
 

Author Comment

by:Adam Trask
ID: 41796212
I left out the part of the code which fill the comboBox because I simply don't know it. The source for the data is the Dictionary Dict.
The data in the Dict instance is retrieved from the Business layer with the code listed below

 public void FillUnitaList()
        {
            //The comboBox gets filled by the Dictionary Object shown above.
            // The abve dictionary object is filled in its turn by the method getAllUnits in the Data layer

            UnitsDepositry unitDepositry = default(UnitsDepositry);
            unitDepositry = new UnitsDepositry();
            unitDepositry.getAllUnits();
            if (unitDepositry.myDict.Count > 0)
            {
               foreach(var pair in unitDepositry.myDict)
                {
                    var theKey = pair.Key; // Create a variable to hold the keys
                    var sName = pair.Value; // Create a variable to hold the Values
                    Dict.Add(theKey, sName);
                }

The Business layer code in turn access the data layer which retrieves the data for the database and place it in another Dictionary instance called myDict:


  public void getAllUnits()
        {
           
            SqlConnection con = default(SqlConnection);
            SqlCommand comm = default(SqlCommand);
            con = new SqlConnection("Server=TARIQ_MEDIA;Database=Trial;integrated security=True");
            comm = new SqlCommand("Select UnitID, UnitName from Units", con);
            con.Open();
            SqlDataReader reader = comm.ExecuteReader();
            while (reader.Read())
            {
                myDict.Add(Convert.ToInt16(reader["UnitID"]),Convert.ToString(reader["UnitName"]));
 
            }
            reader.Close();
            con.Close();
        }
0
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 41796442
Why not simply attach the dictionary as the combobox's datasource; e.g. -

Form1.cs -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace EE_Q28969490
{
	public partial class Form1 : Form
	{
		Dictionary<string, int> dictionary = new Dictionary<string, int>((from i in Enumerable.Range(0, 30) select new { Key = string.Format("Key{0}", i), Value = i }).ToDictionary(k => k.Key, v => v.Value));

		public Form1()
		{
			InitializeComponent();
		}

		private void OnLoad(object sender, EventArgs e)
		{
			cmbData.DataSource = dictionary.ToList();
			cmbData.DisplayMember = "Key";
		}

		private void OnClick(object sender, EventArgs e)
		{
			Close();
		}

		private void OnSelectedValueChanged(object sender, EventArgs e)
		{
			if (sender is ComboBox)
			{
				var cb = sender as ComboBox;
				if (cb.Equals(cmbData))
				{
					tbKey.Text = ((KeyValuePair<string, int>)cb.SelectedValue).Key;
					tbValue.Text = ((KeyValuePair<string, int>)cb.SelectedValue).Value.ToString();
				}
			}
		}
	}
}

Open in new window

Form1.Designer.cs -
namespace EE_Q28969490
{
	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.cmbData = new System.Windows.Forms.ComboBox();
			this.btnOK = new System.Windows.Forms.Button();
			this.lblKey = new System.Windows.Forms.Label();
			this.tbKey = new System.Windows.Forms.TextBox();
			this.tbValue = new System.Windows.Forms.TextBox();
			this.lblValue = new System.Windows.Forms.Label();
			this.SuspendLayout();
			// 
			// cmbData
			// 
			this.cmbData.FormattingEnabled = true;
			this.cmbData.Location = new System.Drawing.Point(13, 13);
			this.cmbData.Name = "cmbData";
			this.cmbData.Size = new System.Drawing.Size(259, 21);
			this.cmbData.TabIndex = 0;
			this.cmbData.SelectedValueChanged += new System.EventHandler(this.OnSelectedValueChanged);
			// 
			// btnOK
			// 
			this.btnOK.Location = new System.Drawing.Point(197, 73);
			this.btnOK.Name = "btnOK";
			this.btnOK.Size = new System.Drawing.Size(75, 23);
			this.btnOK.TabIndex = 1;
			this.btnOK.Text = "OK";
			this.btnOK.UseVisualStyleBackColor = true;
			this.btnOK.Click += new System.EventHandler(this.OnClick);
			// 
			// lblKey
			// 
			this.lblKey.AutoSize = true;
			this.lblKey.Location = new System.Drawing.Point(13, 43);
			this.lblKey.Name = "lblKey";
			this.lblKey.Size = new System.Drawing.Size(28, 13);
			this.lblKey.TabIndex = 2;
			this.lblKey.Text = "Key:";
			// 
			// tbKey
			// 
			this.tbKey.Location = new System.Drawing.Point(47, 40);
			this.tbKey.Name = "tbKey";
			this.tbKey.ReadOnly = true;
			this.tbKey.Size = new System.Drawing.Size(88, 20);
			this.tbKey.TabIndex = 3;
			// 
			// tbValue
			// 
			this.tbValue.Location = new System.Drawing.Point(184, 40);
			this.tbValue.Name = "tbValue";
			this.tbValue.ReadOnly = true;
			this.tbValue.Size = new System.Drawing.Size(88, 20);
			this.tbValue.TabIndex = 5;
			// 
			// lblValue
			// 
			this.lblValue.AutoSize = true;
			this.lblValue.Location = new System.Drawing.Point(141, 43);
			this.lblValue.Name = "lblValue";
			this.lblValue.Size = new System.Drawing.Size(37, 13);
			this.lblValue.TabIndex = 4;
			this.lblValue.Text = "Value:";
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(284, 108);
			this.Controls.Add(this.tbValue);
			this.Controls.Add(this.lblValue);
			this.Controls.Add(this.tbKey);
			this.Controls.Add(this.lblKey);
			this.Controls.Add(this.btnOK);
			this.Controls.Add(this.cmbData);
			this.Name = "Form1";
			this.Text = "Form1";
			this.Load += new System.EventHandler(this.OnLoad);
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		private System.Windows.Forms.ComboBox cmbData;
		private System.Windows.Forms.Button btnOK;
		private System.Windows.Forms.Label lblKey;
		private System.Windows.Forms.TextBox tbKey;
		private System.Windows.Forms.TextBox tbValue;
		private System.Windows.Forms.Label lblValue;
	}
}

Open in new window

Produces the following output -

Initial load -Capture.JPGChoosing another item -Capture.JPG-saige-
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:Adam Trask
ID: 41796815
Hi Saige,

Thanks for your help.
I have been struggling for the last several hours to understand your code, and, to tell you the truth, I couldn't understand every part of it.

However, the man idea was to to simply attach the ComboBox to the dictionary as its data source.
This I managed to do, combining what I understood from your code with what I had.

Now, the data representing the value side in the dictionary  is displayed by the combo box, but I can't seem to find a way to display those values or the keys on the form's text boxes.
0
 

Author Comment

by:Adam Trask
ID: 41796818
Here is the code:
 public partial class FrmADDNewCleaningJob : Form
    {
        string tbKey, tbValue;
        public FrmADDNewCleaningJob()
        {
            InitializeComponent();
        }
       
        private void FrmADDNewCleaningJob_Load(object sender, EventArgs e)
        {
            RetrieveAllUnits getUnits = default(RetrieveAllUnits);
            getUnits = new RetrieveAllUnits();
            getUnits.FillUnitaList();
            if (getUnits.Dict.Count > 0)
            {
                cmbData.DataSource = getUnits.Dict.ToList();
                cmbData.DisplayMember = "Value";
            }
            else
            {
                MessageBox.Show("We have a problem");
            }
        }
       
        private void OnSelectedValueChanged(object sender, EventArgs e)
        {
            if (sender is ComboBox)
            {
                var cb = sender as ComboBox;
                if (cb.Equals(cmbData))
                {
                    tbKey = ((KeyValuePair<string, int>)cb.SelectedValue).Key;
                    tbValue = ((KeyValuePair<string, int>)cb.SelectedValue).Value.ToString();
                    this.txtUnitName.Text = tbKey;
                    this.txtComments.Text = tbValue;
                }
            }
0
 

Author Comment

by:Adam Trask
ID: 41797069
OK, I finally got it... Thank you very much
0
 

Author Closing Comment

by:Adam Trask
ID: 41797070
Excellent... thanks!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

861 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

22 Experts available now in Live!

Get 1:1 Help Now