01 October 2009

DataSource in ListBox and ComboBox

In VB.NET, both ComboBox and ListBox controls allow the software developer to define the DataSource.

However, there might be some errors occur if the way to define the DataSource is not correct.

Sequence to define DataSource and columns name

You are recommended to define the DataSource by the following sequence.

.DisplayMember = mstrDisplayMember
.ValueMember = mstrValueMember
.DataSource = objDS.Tables(0)

Beside that, always make sure that the value for .DisplayMember and .ValueMember are pointing to the correct columns name.


What happen if the sequence is wrong and the ValueMember is pointing to incorrect column name?

Some software developers prefer to put ".DataSource = objDS.Tables(0)" at the first line. If the value of the .ValueMember is incorrect, then VB.NET will prompt you an error message.

Example:

.DataSource = objDS.Tables(0)
.DisplayMember = mstrDisplayMember
.ValueMember = "Incorrect Column Name"

Error message = "Cannot bind to the new value member. Parameter name: value"


What happen if the sequence is correct but DisplayMember and ValueMember are pointing to incorrect columns name?

VB.NET will not prompt you any error message but the result in the controls will be displayed as "System.Data.DataRowView".

Example:

.DisplayMember = mstrDisplayMember
.ValueMember = "Incorrect Column Name"
.DataSource = objDS.Tables(0)

Result = System.Data.DataRowView (if the result returned 3 records, then VB.NET will show you 3 "System.Data.DataRowView")

No comments: