Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all articles
Browse latest Browse all 2535

Can't set comboBox value that has valueMember / displayMember

$
0
0

Hello All,

I'm working on a project where I'm dynamically building a form according to a configuration schema. I'm pretty new at C# and got the following issue I can't get sorted out . 

Any help, advise would be great !!!

When building a ComboBox I can't set the value I want !!

Probably I'm missing something.

I've tried several methods but nothing does it ... below my code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ComboBoxSample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            CreateComboBox();
        }
        public void CreateComboBox(){

            //Working variables
            string valueMember = "idColumn";
            string displayMember = "valueColumn";

            //Create a panel and add to the form
            TableLayoutPanel tlp = new TableLayoutPanel();
            this.Controls.Add(tlp);

            //Create the data source
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add(valueMember, typeof(string));
            dataTable.Columns.Add(displayMember, typeof(string));
            dataTable.Rows.Add("A", "value A");
            dataTable.Rows.Add("B", "value B");
            dataTable.Rows.Add("C", "value C");


            //Create a binding source
            BindingSource bindingSource = new BindingSource(dataTable, null);

            //Create a comboBox and bind the datasource
            ComboBox comboBox = new ComboBox();
            comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox.DataSource = bindingSource;
            comboBox.ValueMember = valueMember;
            comboBox.DisplayMember = displayMember;

            /*********************************
                 Try and set the value
            **********************************/

            //No methode  displays  B --> combo stays on  A
            comboBox.SelectedValue = "B";
            //comboBox.Text = "value B";
            //comboBox.SelectedItem = comboBox.FindStringExact("value B");

            //add the controles to the panel
            tlp.Controls.Add(comboBox, 0, 0);

        }
    }
}




Viewing all articles
Browse latest Browse all 2535

Trending Articles