Friday, May 29, 2015

Retrieve Images from SQL Server Database into Data Grid in WPF using Data Binding


In this article we will see how to store and retrieve images from SQL Server Database into Data Grid in WPF using Data Binding. I am creating the database using code first approach. Now we will look into the System requirements.
System Requirements:

·         Microsoft Visual Studio 2010.
·         SQL Server 2008 R2.
Now we will look into design part and it is shown below:

I have taken a class named Image Class and its property is shown below.
 public class ImageClass
    {
        public int Id { get; set; }
        public string ImagePath { get; set; }
        public byte[] ImageInBytes { get; set; }
    }
In the above class Id property is the primary key, Image Path property will take the path of image from system which you will browse and ImageToByte property will store the image in the form of array of bytes.
The Xaml code for binding data grid is shown below

<DataGrid AutoGenerateColumns="False" Height="248" HorizontalScrollBarVisibility="Auto" HorizontalAlignment="Left" Margin="94,153,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="399" Background="#FFFFE2E2" >
<DataGrid.Columns>
  <DataGridTextColumn Header="Id" Binding="{Binding Path=Id}"  Width="80"/>
  <DataGridTextColumn Header="ImagePath" Binding="{Binding Path=ImagePath}" Width="80" />
       <DataGridTemplateColumn Header="Image" Width="80" IsReadOnly="True"  >
           <DataGridTemplateColumn.CellTemplate>
             <DataTemplate>
                 <Image Source="{Binding Path=ImageInBytes}" Width="60" Height="60" />
              </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
  </DataGrid.Columns>
 </DataGrid>
Working:
The below snapshot shows how application looks when you are ready for uploading image file into database


The following are the steps to upload or store an image into SQL database

Step 1:

 Click on browse button, Browse the picture using open dialog window and it is shown in      below snapshot




Step 2:
The preview of image is shown in image control then click on upload button and it is shown in below snapshot



Step 3:
 Refresh the data grid then image uploaded will be shown in data grid



Summary: In this article I have shown how to shown an image into data grid from database. I have uploaded the source code also. If you have any queries regarding this article please do comment. Thanks for reading my article.

Source Code :Download





No comments: