Can't set comboBox value that has valueMember / displayMember

  • Thread starter Thread starter Jérôme CLAUDE
  • Start date Start date
J

Jérôme CLAUDE

Guest
Hello All,

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

Any help, advise would be great !!!

When building a ComboBox I cant set the value I want !!

Probably Im missing something.

Ive 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);

}
}
}

Continue reading...
 
Back
Top