Monday, April 21, 2008

Databinding issues on the Compact Framework <= 2.0

I had a requirement the other day to databind an alphanumeric id - reasons for which are not that important. What is important is that setting the ValueMember property to the alaphanumeric string is fine, but setting the SelectedValue to the alphanumeric value doesn't work on Visual Studio 2005 running any version of the Compact Framework. This however does work on the desktop (2.0 - not tried 1.1).

Whats more, this seems to be fixed in Visual Studio 2008 regardless whether you target CF 2.0 or CF 3.5.

The failing code was tested on CF 2.0 SP2. The code worked on VS 2008 CF 2.0 and CF 3.5.

A simple work around that I quickly knocked up (if you are still targeting CF 2.0 with VS 2005) is illustrated as follows:-

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

List list = new List();
MyData mydata = new MyData();
mydata.Id = "1";
mydata.Desc = "Desc 1";
list.Add(mydata);

MyData mydata2 = new MyData();
mydata2.Id = "2";
mydata2.Desc = "Desc 2";
list.Add(mydata2);

//Now bind the list to our combo box.
comboBox1.DataSource = list;

comboBox1.DisplayMember = "Description";
comboBox1.ValueMember = "Id";

//DOES NOT WORK ON VS 2005 (CF 2.0) comboBox1.SelectedValue = "2";
//This does work.
comboBox1.SelectedValue = Convert.ToInt32(mydata2.Id);
}
}

public class MyData
{
private string id;
private string desc;

public string Id
{
get
{
return id;
}
set
{
id = value;
}
}

public string Description
{
get
{
return desc;
}
set
{
desc = value;
}
}
}

No comments: