Combobox is used to display a collection of items.In Combobox control only one item is visible at a time.Whichever item is selected is visible ,others are hidden.User can click the combox and select any other item from the list of items.
Like the datagrid control,comobox is also a ItemsControl ,as it derives from the ItemsControl base class.ItemsControl is base class for controls which displays collection of items.
To add combobox in XAML we can use the code as below:
<ComboBox Name="cmbListProducts" Height="20px"> <ComboBoxItem Content="Electronics" IsSelected="True"></ComboBoxItem> <ComboBoxItem Content="Household"></ComboBoxItem> <ComboBoxItem Content="Hardware"></ComboBoxItem> <ComboBoxItem Content="Automobiles"></ComboBoxItem> <ComboBoxItem Content="Clothes"></ComboBoxItem> </ComboBox>
Single item in the combobox is represent by the ComboBoxItem element.We are adding the items here at design time.Usually combobox is populated at run time.
Populating combobox at run time is as simple as setting the ItemsSource property of the combobox.
<ComboBox Name="cmbListProducts" Height="20px"> </ComboBox>
and then in the codebehind we just set the itemsource property
public void BindStudents() { List<string> lstProducts = new List<string>{ "Electronics","Household","Hardware","Automobiles","Clothes" }; cmbListProducts.ItemsSource = lstProducts; }
Here we are binding to a simple list of string values.
Binding combobox to list of objects
In the previous example we had a list of string values which we have bound to the combobox.Sometimes we need to bind a collection of objects.
We can bind combobox to a list of object values by setting some of the combobix properties:
- DisplayMemberPath
- SelectedValuePath
- SelectedValue
<ComboBox Name="cmbListProducts" Height="20px" DisplayMemberPath="name" SelectedValuePath="Name" SelectedValue="{Binding Path=name}"> </ComboBox>
We are fetching the product list from the Products table which consists of other columns such as price.We need to tell combobox which columns we want to display in the combobox.We use the DisplayMemberPath to select the column which we want to display in the combobox.
public void BindProducts() { string ConString = @"Data Source=SHRADHA\SQLEXPRESS;Initial Catalog=test1;Integrated Security=True;";//ConfigurationManager.ConnectionStrings ["ConString"].ConnectionString; string CmdString = string.Empty; using (SqlConnection con = new SqlConnection(ConString)) { CmdString = "SELECT name,price FROM Products"; SqlCommand cmd = new SqlCommand(CmdString, con); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable("products"); sda.Fill(dt); cmbListProducts.ItemsSource = dt.DefaultView; } }
Leave a Reply