Skip to main content
WPF Listbox Binding from MS SQL Database 02

WPF MVVM Listbox SelectionChanged Get SelectedItem

Let’s see how we can get SelectedItem from a WPF Listbox using MVVM methodology. WPF MVVM Listbox SelectionChanged Get SelectedItem.

In this example, I will be binding the WPF Listbox from MS SQL Database using MVVM ViewModel and ObservableCollection. The logic is quite simple. I’m passing a class item to ViewModel of type from which ListBox is bound to. And the WPF ViewModel will be assign a String value to the WPF TextBlock to show the selectedItem on the View.

Data is fetched from MS SQL Database table : tblCountries

WPF MVVM Listbox SelectionChanged Get SelectedItem 01

So make a WPF design Page as below :

MainWindow.xaml : 

<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="#fff"
Title="WPF ListBox from MS SQL Database" Height="350" Width="525" WindowState="Maximized" WindowStyle="ThreeDBorderWindow">
<StackPanel Orientation="Vertical">
<TextBlock Text="WPF ListBox from MS SQL Database" FontSize="25" FontWeight="Bold" Margin="5" HorizontalAlignment="Left"/>
<ListBox Name="lstBox" HorizontalAlignment="Left" VerticalAlignment="Center" ItemsSource="{Binding countries}"
SelectionChanged="lstBox_SelectionChanged"
Background="#fff">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" >
<TextBlock Text="{Binding id}" Margin="2" FontWeight="Bold"/>
<TextBlock Text="{Binding country}" Margin="2" />
<TextBlock Text="{Binding ondate}" Margin="2"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Text="{Binding txtSelectedItem}" Margin="5"/>
</StackPanel>
</Window>

ListBox ItemSource and SelectionChanged method is defined in the design code and a TextBlock is made to show the SelectedItem.

Edit the code file as below :

MainWindow.xaml.cs : 

using System.Windows;
using System.Windows.Controls;
using WpfApplication2.Model;
using WpfApplication2.ViewModel;

namespace WpfApplication2
{
public partial class MainWindow : Window
{
CountriesViewModel co;
public MainWindow()
{
InitializeComponent();
co = new CountriesViewModel();
base.DataContext = co;
}

private void lstBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = (ListBox)sender;
co.SelectedItem((Countries)item.SelectedItem);
}
}
}

Make two folders with name Model and ViewModel respectively. And create two classes as below:

Model > Countries.cs : 

using System;

namespace WpfApplication2.Model
{
public class Countries
{
public int id { get; set; }
public string country { get; set; }
public DateTime ondate { get; set; }

}
}
</pre >

ViewModel > CountriesViewModel .cs : 

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using WpfApplication2.Model;

namespace WpfApplication2.ViewModel
{
public class CountriesViewModel : INotifyPropertyChanged
{
static String connectionString = @"Data Source=vibes\sqlexpress;Initial Catalog=ParallelCodes;User ID=sa;Password=789;";
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter adapter;
DataSet ds;
public ObservableCollection<Countries> countries { get; set; }
public String txtSelectedItem {get;set;}
public CountriesViewModel()
{
txtSelectedItem = "Please select a country";
FillList();
}

public void FillList()
{
try
{
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand("select * from tblCountries", con);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds, "tblCountries");

if (countries == null)
countries = new ObservableCollection<Countries>();

foreach (DataRow dr in ds.Tables[0].Rows)
{
countries.Add(new Countries
{
id = Convert.ToInt32(dr[0].ToString()),
country = dr[1].ToString(),
ondate = Convert.ToDateTime(dr[2].ToString())
});
}
}
catch (Exception ex)
{

}
finally
{
ds = null;
adapter.Dispose();
con.Close();
con.Dispose();
}
}

public void SelectedItem(Countries country)
{
txtSelectedItem = "You Selected " + country.country + "(ID: " + country.id + ", added on Date : " + country.ondate + ")";
OnPropertyChanged("txtSelectedItem");
}

#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}

Thank You.

Also see :

WPF Datagrid with Button and Click Method

WPF Designing Material Design Tabs with Dragablz

WPF Button Style with Rounded Corners and Hover Effects

WPF Textbox With Rounded Corners

WPF Textbox Style – Changing Colors on Focus

WPF ComboBox SelectionChanged – SelectedItem Method

WPF Listbox Binding from MS SQL Database and SelectionChangedMethod