ComboBox CodeSample - Populating multiple ComboBoxes that all use the same DataSource
From Visual WebGui Wiki
| This article will have a few sections added to it soon, based on the following article type skeleton: NewCodeSampleTemplate |
Contents |
Overview
This CodeSample will demonstate how you can populate multiple ComboBoxes that all use the same DataSource, by using DataView.
It also demonstrates the problems with binding multiple ComboBoxes to the same BindingSource instance. Pay special attention to Combobox3 and Combobox4 in the code below, as this method of binding will not work correctly. Runtime, both of these ComboBoxes will show the same selected value, the one last selected for either of the controls.
VB.NET code
Imports Gizmox.WebGUI.Forms Public Class ComboAndSameDatasource Private DT As DataTable Private BS As BindingSource Private Sub ComboAndSameDatasource_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load DT = New DataTable DT.Columns.Add("ID", GetType(String)) DT.Columns.Add("Name", GetType(String)) DT.Rows.Add("1", "One") DT.Rows.Add("2", "Two") DT.Rows.Add("3", "Three") DT.Rows.Add("4", "Four") DT.Rows.Add("5", "Five") BS = New BindingSource CType(BS, System.ComponentModel.ISupportInitialize).BeginInit() CType(BS, System.ComponentModel.ISupportInitialize).EndInit() BS.DataSource = DT For Each cb As ComboBox In New Object() {ComboBox1, ComboBox2} cb.DataSource = New DataView(DT) cb.DisplayMember = "Name" cb.ValueMember = "ID" Next ' This binding will NOT work correctly. For Each cb As ComboBox In New Object() {ComboBox3, ComboBox4} cb.DataSource = BS cb.DisplayMember = "Name" cb.ValueMember = "ID" Next End Sub End Class
C# Code
| The conversion of this code to C# has not been completed yet. Please feel free to contribute and add contents to the Wiki |
