.NET Framework Bookmark and Share   
 index > Windows Presentation Foundation (WPF) > Display items in listbox from database
 

Display items in listbox from database

hello.

I wonder how i dispaly all colums from a datbase tabel. I know how the sql string should look like "select * from tabel" for exampel but how do i get them in the listbox.
Alcstudio
steveareno
Hi Good morning,


I will give u example for this question through that you have to solve u r problem.

Once application is created it will give you some default files as below

  • app.config
  • app.xaml
  • window1.xam

Here we will be dealing with "window1.xaml" file, idea is to bind listbox with database. I am using MS-Access database.

Table structure is as:

empId autonumber
empName text

"window1.xaml" code is as below

< Window x : Class ="WindowsApplication1.Window1"

xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns : x ="http://schemas.microsoft.com/winfx/2006/xaml" Title ="WindowsApplication1" Height ="277" Width ="356">

< ListBox Width ="200" Margin ="10" ItemsSource ="{Binding Path=emp}" Name ="lstEmployee">

< ListBox.ItemTemplate >

< DataTemplate >

< StackPanel >

< TextBlock Text ="{Binding Path=empId}" />

< TextBlock Text ="{Binding Path=empName}" />

</ StackPanel >

</ DataTemplate >

</ ListBox.ItemTemplate >

</ ListBox >

</ Window >

Code behind file is as:

"window1.xaml.cs":

using System;

using System.Collections.Generic;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Data;

using System.Data.OleDb;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

namespace WindowsApplication1

{

/// <summary>

/// Interaction logic for Window1.xaml

/// </summary>

public partial class Window1 : System.Windows.Window

{

public OleDbConnection oleCon;

public OleDbCommand oleComd;

string strSql = "SELECT * FROM emp" ;

public Window1()

{

InitializeComponent();

BindData();

}

public void viewButton_Click(object sender, RoutedEventArgs args)

{

//string strVal = peopleListBox.SelectedValue.ToString();

//MessageBox.Show(strVal);

}

public void BindData()

{

oleCon = new OleDbConnection ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=TestDb.mdb" );

oleComd = new OleDbCommand (strSql,oleCon);

DataSet dtst = new DataSet ();

OleDbDataAdapter adpt = new OleDbDataAdapter ();

try

{

oleCon.Open();

adpt.SelectCommand = oleComd;

adpt.Fill(dtst,"emp" );

lstEmployee.DataContext = dtst;

}

catch (Exception ex)

{

//lblMessage.Content = ex.Message;

}

finally

{

oleCon.Close();

}

}

}

}

The Binding in the listbox simply instructs the binding to get the data from the DataContext of the parent (in this case, it walks up the control tree until it finds a DataContext in the Window)

To show the employee names in the listbox, we create bindings in the ItemsTemplate to show the FirstName from the Dataset.

< ListBox.ItemTemplate >

< DataTemplate >

< StackPanel >

< TextBlock Text ="{Binding Path=empId}" />

< TextBlock Text ="{Binding Path=empName}" />

</ StackPanel >

</ DataTemplate >

</ ListBox.ItemTemplate >

Next, we add text boxes to hold our name like this

< TextBlock Text ="{Binding Path=empName}" />



Hope It Helps To you if you got solution please vote for me

Thanks ,

Chaitanya Narne
chaitanyanarne
Hi i will give some other example also here i wrote a method bind
listbox there i bind data to listbox from sql server the code is on vb.net
now i am giving that code below

first i give a xaml file.

<Window x:Class ="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="400" Width="550" >
<Window.Resources>
<DataTemplate x:Key="CustomerTemplate" >
<Border BorderThickness="2" BorderBrush="silver" CornerRadius="5" Padding="1" Width="500"
HorizontalAlignment="Center" VerticalAlignment="Center" >
<Grid>
<TextBlock Text="{Binding CompanyName}" Foreground="#515151"
FontSize="16" HorizontalAlignment="Left"
FontWeight="Bold" />
<TextBlock Text="{Binding ContactTitle}" Foreground="#515151" Margin="0,25,0,0"
FontSize="10" HorizontalAlignment="Left"
FontWeight="Bold" />
<TextBlock Text="{Binding Address}" Foreground="#515151" Margin="0,40,0,0"
FontSize="10" HorizontalAlignment="Left"
/>
</Grid>
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox Name="ListBox1" ItemsSource="{Binding}"
ItemTemplate="{StaticResource CustomerTemplate}" Margin="0,0,0,30" >
</ListBox>
<Button HorizontalAlignment="Left" Name="Button1"
Width="75" Height="23" VerticalAlignment="Bottom" >Button</Button>
</Grid>
</Window>



now i am giving you .vb file below

Imports System.Data.SqlClient
Imports System.Data
Class Window1
Private Sub Button1_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
'Orders
BindData()
End Sub
Private Sub BindData()
ListBox1.DataContext = GetData().Tables(0)
MsgBox("DONE" )
End Sub
Private Function GetData() As DataSet
Dim NwndConString As String = "Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Persist Security Info=True;Trusted_Connection=True "
Dim conNwnd As New SqlConnection(NwndConString)
Dim strSelect As String = "Select * from Customers"
Dim adaNwnd As New SqlDataAdapter(strSelect, NwndConString)
Dim dsNwnd As New DataSet
adaNwnd.Fill(dsNwnd)
Return dsNwnd
End Function
End Class


If this helps to you please vote for me

thanks

chaitanyanarne
Hi i have been changing the connection using MySql instead of Access.
I wonder where whit part come in the peoplelistbox


//string strVal = peopleListBox.SelectedValue.ToString();

//MessageBox.Show(strVal);


i cant see any items in the list.


Here is the code:


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Data;
using System.Data.OleDb;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;


namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public MySqlConnection mysqlCon;
        public MySqlCommand mysqlComd;
        
        string strSql = "SELECT * FROM blogs";

        public Window1()
        {
            InitializeComponent();
            BindData();
        }
        public void viewButton_Click(object sender, RoutedEventArgs args)
        {
            //string strVal = peopleListBox.SelectedValue.ToString();
            //MessageBox.Show(strVal);
        }
        public void BindData()
        {
            mysqlCon = new MySqlConnection("server=; user id=; password=; database=; pooling=false; port=3306;");
            mysqlComd = new MySqlCommand(strSql, mysqlCon);
            DataSet dtst = new DataSet();
            MySqlDataAdapter adpt = new MySqlDataAdapter();
            try
            {
                mysqlCon.Open();
                adpt.SelectCommand = mysqlComd;
                adpt.Fill(dtst, "blogs");
                Employee.DataContext = dtst;
            }
            catch (Exception ex)
            {
                //lblMessage.Content = ex.Message;
            }
            finally
            {
                mysqlCon.Close();
            }
        }

    }
}


Alcstudio
Hi,
You should do the following changes:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Data;
using System.Data.OleDb;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;


namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public MySqlConnection mysqlCon;
public MySqlCommand mysqlComd;

string strSql = "SELECT * FROM blogs";

public Window1()
{
InitializeComponent();
BindData();
}
public void viewButton_Click(object sender, RoutedEventArgs args)
{
//string strVal = peopleListBox.SelectedValue.ToString();
//MessageBox.Show(strVal);
}
public void BindData()
{
mysqlCon = new MySqlConnection("server=; user id=; password=; database=; pooling=false; port=3306;");
mysqlComd = new MySqlCommand(strSql, mysqlCon);
DataSet dtst = new DataSet();
MySqlDataAdapter adpt = new MySqlDataAdapter();
try
{
mysqlCon.Open();
adpt.SelectCommand = mysqlComd;
adpt.Fill(dtst, "blogs");

DataTable dt = dtst.Tables[0];
Employee.ItemsSource = dt;
}
catch (Exception ex)
{
//lblMessage.Content = ex.Message;
}
finally
{
mysqlCon.Close();
}
}

}
}

Regards,

Federico Benitez
My blog
Federico Benitez
iam getting error here:

Employee.ItemsSource = dt;

Error:
Cannot implicitly convert type 'System.Data.DataTable' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?)


Alcstudio
Hi,

Employee.ItemsSource = dt.Rows;

Regards,

Federico Benitez
My blog
Federico Benitez
Still dont get anything in my list.
Have i missed something.
Alcstudio
My XAML looks like this:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="371" Width="356">
    <Grid Margin="24,10,12,10">
		<ListBox Width ="200" ItemsSource="{Binding Path=blogs}" x:Name ="Employee" Margin="0,0,104,0">
			<ListBox.ItemTemplate>
				<DataTemplate>
					<StackPanel>
						<TextBlock Text ="{Binding Path=user_ID}" />
						<TextBlock Text ="{Binding Path=title}" />
					</StackPanel>
				</DataTemplate>
			</ListBox.ItemTemplate>
            <ListBoxItem />
        </ListBox>
		<Button x:Name="viewButton" HorizontalAlignment="Right" Margin="0,132,12,87" Width="72" Content="Button" Click="viewButton_Click" />
	</Grid>
</Window>

Alcstudio

Hi,
Are you sure your column names are "user_ID" and "title"?

Regards,


Federico Benitez
My blog
Federico Benitez
yes.

And the tabel name is "blogs"
Alcstudio

if you are doing the binding in to the itemsSource in code to the table.Rows remove in the XAML ItemsSource="{Binding Path=blogs}"

Regards,


Federico Benitez
My blog
Federico Benitez
ok, still dont see any thing so i post all the code again =):
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="371" Width="356">
    <Grid Margin="24,10,12,10">
		<ListBox Width ="200" ItemsSource="{Binding Path=blogs}" x:Name="Blogs" Margin="0,0,104,0">
			<ListBox.ItemTemplate>
				<DataTemplate>
					<StackPanel>
						<TextBlock Text ="{Binding Path=user_ID}" />
						<TextBlock Text ="{Binding Path=title}" />
					</StackPanel>
				</DataTemplate>
			</ListBox.ItemTemplate>
        </ListBox>
		<Button x:Name="viewButton" HorizontalAlignment="Right" Margin="0,132,12,87" Width="72" Content="Button" Click="viewButton_Click" />
	</Grid>
</Window>

And here is the code behind:

    public partial class Window1 : Window
    {
        public MySqlConnection mysqlCon;
        public MySqlCommand mysqlComd;

        string strSql = "SELECT * FROM blogs";

        public Window1()
        {
            InitializeComponent();
            BindData();
        }
        public void viewButton_Click(object sender, RoutedEventArgs args)
        {
            //string strVal = peopleListBox.SelectedValue.ToString();
            //MessageBox.Show(strVal);
        }
        public void BindData()
        {
            mysqlCon = new MySqlConnection("server=; user id=; password=; database=; pooling=false; port=3306;");
            mysqlComd = new MySqlCommand(strSql, mysqlCon);
            DataSet dtst = new DataSet();
            MySqlDataAdapter adpt = new MySqlDataAdapter();
            try
            {
                mysqlCon.Open();
                adpt.SelectCommand = mysqlComd;
                adpt.Fill(dtst, "blogs");

                DataTable dt = dtst.Tables[0];
                Blogs.ItemsSource = dt.Rows;
                
            }
            catch (Exception ex)
            {
                //lblMessage.Content = ex.Message;
            }
            finally
            {
                mysqlCon.Close();
            }
        }

    }

Alcstudio

You didnt do what I said in my previous post.

Here is the code:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="371" Width="356">
    <Grid Margin="24,10,12,10">
		<ListBox Width ="200" x:Name="Blogs" Margin="0,0,104,0">
			<ListBox.ItemTemplate>
				<DataTemplate>
					<StackPanel>
						<TextBlock Text ="{Binding Path=user_ID}" />
						<TextBlock Text ="{Binding Path=title}" />
					</StackPanel>
				</DataTemplate>
			</ListBox.ItemTemplate>
        </ListBox>
		<Button x:Name="viewButton" HorizontalAlignment="Right" Margin="0,132,12,87" Width="72" Content="Button" Click="viewButton_Click" />
	</Grid>
</Window><br/>
public partial class Window1 : Window
    {
        public MySqlConnection mysqlCon;
        public MySqlCommand mysqlComd;

        string strSql = "SELECT * FROM blogs";

        public Window1()
        {
            InitializeComponent();
            BindData();
        }
        public void viewButton_Click(object sender, RoutedEventArgs args)
        {
            //string strVal = peopleListBox.SelectedValue.ToString();
            //MessageBox.Show(strVal);
        }
        public void BindData()
        {
            mysqlCon = new MySqlConnection("server=; user id=; password=; database=; pooling=false; port=3306;");
            mysqlComd = new MySqlCommand(strSql, mysqlCon);
            DataSet dtst = new DataSet();
            MySqlDataAdapter adpt = new MySqlDataAdapter();
            try
            {
                mysqlCon.Open();
                adpt.SelectCommand = mysqlComd;
                adpt.Fill(dtst, "blogs");

                DataTable dt = dtst.Tables[0];
                Blogs.ItemsSource = dt.Rows;
                
            }
            catch (Exception ex)
            {
                //lblMessage.Content = ex.Message;
            }
            finally
            {
                mysqlCon.Close();
            }
        }

    }




Regards,
Federico Benitez
My blog
Federico Benitez
Now i have done as you said in yourprevious post.
Still dont see anything.
Alcstudio
Anyone who has any idea concerning this?
Alcstudio
I have checked my code many times now and cant find any errors in the code.

Should i loop from the tabel or something like that?
Alcstudio

Hi,

I have seen the above code, it seems it is correct. If all columns with their row values are to be displayed in LisBox I will do the following:
Step 1: Create a class having public properies same as column names e.g clsBlogs.
Step 2: In Window1.Xaml.cs, write the code for getting data from data table using SqlDataReader(provided using SqlServer).
Step 3: In theWindow1.Xaml.cs, define a public property,of ObservableCollection<clsBolgs> e.g. ColData.
Step 4: Now, put all the dataassiciatedwith the reader in to ObsetvableCollection<clsBlogs>.
Step5:Bind the observable collection to window using following line:

this.DataContaxt=this; //This will set all public properties on the window as DataSource of the Window.
lstData.ItemsSource= ColData;


Step 6: In Xamlcreate DataTemplate, as below:

<DataTemplate x:Key="MyTenplate">
<Textblock Text="{Binding Path=Prop1}"/>
<Textblock Text="{Binding Path=Prop1}"/>
<Textblock Text="{Binding Path=Prop1}"/>
...DO this for all those columns which you want todisplay in ListView Prop(n) represents the public property of the clsBlogs class.
</DataTemplate>

Step 7: Inxaml for the List box Set followingm properties

<ListBox ItemTemplate="{StaticResource MyTenplate}">

Just try this, it will work.


Thanks

Mahesh Sabnis

Mahesh Sabnis
The Class should it look something like this?

public class clsBlogs
{
TextBlock.Text = "user_ID";
TextBlock.Text = "title";
}
Alcstudio
Hello again.

I should need some help with the steps.

Iam using MySQL so you know.
Alcstudio
Hi Alcstudio,

You can set the DataContext property instead.

try
{
mysqlCon.Open();
adpt.SelectCommand = mysqlComd;
adpt.Fill(dtst, "blogs");

DataTable dt = dtst.Tables[0];
Blogs.DataContext = dt;

}


<ListBox Width ="200" x:Name="Blogs" Margin="0,0,104,0" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text ="{Binding Path=user_ID}" />
<TextBlock Text ="{Binding Path=title}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>


Best Regards,
Zhi-Xin



Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework!
Zhi-Xin Ye
I have done as your example but still nothing
Alcstudio
Hi Alcstudio,

Please check the following points:

1. Is there any data in the "dt"? You can set a breakpoint at this line:

Blogs.DataContext = dt;

and check whether there is any data in the "dt";

2. If the ListBox is bound to the DataTable instead of DataSet, the ItemsSource property should be set to "{Binding}", i.e.

<ListBox Width ="200" x:Name="Blogs" Margin="0,0,104,0" ItemsSource="{Binding}" >

3. Make sure the "user_ID" and "title" are the same with the field name in the table.

Best Regards,
Zhi-Xin



Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework!
Zhi-Xin Ye
The xaml looks like this:

<Window x:Class="ShowListBoxDataBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<ListBox x:Name="Blogs" Margin="21,12" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text ="{Binding Path=user_ID}" />
<TextBlock Text ="{Binding Path=title}" />
<TextBlock Text ="{Binding Path=message}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>

If i set a Breakpoint at "Blogs.DataContext = dt;" what should happen then its just get red and cant see any info.

The "user_ID" and "title" are the same as in the table.
Alcstudio

If i set a Breakpoint at "Blogs.DataContext = dt;" what should happen then its just get red and cant see any info.

When the program breaks, move the mouse over the "dt", a dropdown would show up, check whether the Rows count is empty.

Best Regards,
Zhi-Xin



Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework!
Zhi-Xin Ye
When i have the mouse over "DataContext" i get following:

"object FramworkElement.DataContext
Gets or sets the data context for an element when it paticipates in databinding.
This is a dependency property."

When i have mouse over "dt" i get following:

"(local variable) DataTable dt"
Alcstudio
Hi Alcstudio,

I think you should study some basic debugging knowledge first, you can start from here: Viewing Data in the Debugger .

Best Regards,
Zhi-Xin


Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework!
Zhi-Xin Ye
Ok thanks. I will write when i know the answer
Alcstudio

You can use google to search for other answers

Custom Search

More Threads

• WPF GridView check box conversion
• Flickering in 3D
• Creating a RoutedEvent using reflection on an object
• Binding to Foreign Key doesn't Bind to Source?
• Dependency Property -More details pls
• Compatability
• When to apply transform to panel's children
• Forms Authentication WPF
• WPF + string resources
• Freezable Warning in Debug output window