Thursday, 15 August 2013

How to get the selected value of a databound winforms ComboBox control (C #)

I have discussed early about loading data to a dictionary and data binding it to a winforms combobox control.
Now its time to get that selected value from that combo box

There are many ways to get the values from the combobox but I have 2 favorite ways.

* Using the combobox's "selection change committed" or
* "Selected index changed"

Now if you are using the selected "Selected index changed" event handler, you must understand that this will trigger in the initial form load and it might lead up to some nasty errors. Its better to use a lock and update the lock once the page load is complete( well don't really have to go in a extreme worry).
Heres an example
(lets edit code from a previous example)

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;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        bool loadComplete = false;
        public Form1()
        {
            InitializeComponent();
            loadComboElements();

            loadComplete = true;//notice that load comlete will be true
                                // only when items are loaded to combobox...

            getSelectedValue();//now with this method then inicial selected value is displayed
        }

        private void loadComboElements()
        {
            Dictionary<int, string> keyValueDic = new Dictionary<int, string>();
            keyValueDic.Add(-1, "Please select an item");
            keyValueDic.Add(1, "sample item 1");
            keyValueDic.Add(2, "Sample item 2");

            comboBox1.DataSource = keyValueDic.ToList();
            comboBox1.DisplayMember = "VALUE";
            comboBox1.ValueMember = "Key";
            comboBox1.SelectedValue = -1;//seddinng the initial selected value
        }

       //double click the combo box and the method skeleton will be built
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            getSelectedValue();
        }

        private void getSelectedValue()
        {
            if (loadComplete == true)
            {
                int selectedValueFromComobox;
                bool isValidInt = int.TryParse(Convert.ToString(comboBox1.SelectedValue), out selectedValueFromComobox);
                if (isValidInt)
                {
                    label1.Text = Convert.ToString(selectedValueFromComobox);
                }
            }
        }
    }
}

No comments:

Post a Comment