• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 175
  • Last Modified:

Using AddRange to populate comboBox with data stored in a Dictionary

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
Adam Trask
Asked:
Adam Trask
  • 5
1 Solution
 
AndyAinscowFreelance programmer / ConsultantCommented:
>>This is my first time trying to use the comboBox AddRange method in C#.

Your code snippet doesn't use that anywhere.
0
 
Adam TraskAuthor Commented:
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
 
it_saigeDeveloperCommented:
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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
Adam TraskAuthor Commented:
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
 
Adam TraskAuthor Commented:
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
 
Adam TraskAuthor Commented:
OK, I finally got it... Thank you very much
0
 
Adam TraskAuthor Commented:
Excellent... thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now