?
Solved

Using AddRange to populate comboBox with data stored in a Dictionary

Posted on 2016-09-13
7
Medium Priority
?
128 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 45

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 35

Accepted Solution

by:
it_saige earned 2000 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses
Course of the Month9 days, 18 hours left to enroll

571 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