Wednesday, December 10, 2008

.NET ComboBox shows data type

I've been using a data bound ComboBox in one of my apps, and I discovered that under certain conditions, the ComboBox would display "System.Data.DataRowView" instead of my values. in other words, it was showing the data type instead of my content.

in this case, I'm binding an XML file to a DataSet and then showing the content in a ComboBox (C#). the issue occurred when I had more than one child element in the XML.

this is my original (non-working) code (xmlQueries is a DataSet object):

xmlQueries.ReadXml(filePath);
comboBoxXpath.ValueMember = "XpathQuery";
comboBoxXpath.DisplayMember = "XpathQuery";
// Note: set the datasource after the properties
comboBoxXpath.DataSource = xmlQueries.Tables[0];

thankfully, the Visual Studio debugger showed me the light, it turned out that the DataSet column name was changing (to "XpathQuery_Text") when I had more that one value in my XML. the solution was to read the column name dynamically:

xmlQueries.ReadXml(filePath);
// Read column name dynamically
comboBoxXpath.ValueMember = xmlQueries.Tables[0].Columns[0].ToString();
comboBoxXpath.DisplayMember = xmlQueries.Tables[0].Columns[0].ToString();
// Note: set the datasource after the properties
comboBoxXpath.DataSource = xmlQueries.Tables[0];

No comments: