Site icon ParallelCodes

WPF Listbox Binding from MS SQL Database

Let’s see how we can Bind WPF Listbox from MS SQL Database.

WPF Listbox can be filled from database using IList which contains items fetch from Database. In the below WPF example I will be binding it using IList and MS SQL Database.

My Database table : tblCountries

Code :

 

WPF Listbox Binding from MS SQL Database. Make a WPF Listbox in your WPF Form as below :

<ListBox Name="lstBox" HorizontalAlignment="Left" VerticalAlignment="Center"
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>

Open your code page (.cs page) and write the below code to fill WPF Listbox from MS SQL Database.

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();
}
}

This will Bind our WPF Listbox from MS SQL Database server table :

Complete Design and Code :

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>

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; }

}
}

For getting selectedItem or selection from the users, please see this post on WPF Listbox – Getting SelectedItem.

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


Exit mobile version