WPF Listbox SelectionChanged – Get SelectedItem

  • by
WPF Listbox Binding from MS SQL Database 02

Let’s see how we can get WPF Listbox SelectedItem and use it for displaying in a WPF Messagebox. To see How to Bind WPF Listbox from Database please visit this Post. WPF Listbox SelectionChanged – Get SelectedItem

WPF Listbox SelectionChanged - Get SelectedItem 02

Make a simple Listbox in your WPF form 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"
Background="#fff" SelectionChanged="lstBox_SelectionChanged_1" >
<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>
</StackPanel>
</Window>

SelectionChanged method will be called when the user changes and selects an item from our WPF Listbox. And for getting the selected item here is the code :

private void lstBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
var item = (ListBox)sender;
var country = (Countries)item.SelectedItem;
MessageBox.Show("You Selected " + country.country + "(ID: " + country.id + ", added on Date : " + country.ondate + ")");
}

I’m having a Countries class which I’m using to Bind my WPF Listbox from Database.

Here is the complete code :

MainWindow.xaml.cs :

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
static String connectionString = @"Data Source=vibes\sqlexpress;Initial Catalog=ParallelCodes;User ID=sa;Password=789;";
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter adapter;
DataSet ds;
SqlDataReader reader;

public MainWindow()
{
InitializeComponent();
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");
Countries co = new Countries();
IList<Countries> co1 = new List<Countries>();

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

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

private void lstBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
var item = (ListBox)sender;
var country = (Countries)item.SelectedItem;
MessageBox.Show("You Selected " + country.country + "(ID: " + country.id + ", added on Date : " + country.ondate + ")");
}
}

public class Countries
{
public int id { get; set; }
public string country { get; set; }
public DateTime ondate { get; set; }

}
}

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