dhanlak 0 Newbie Poster


I am trying to bind a datagrid with a datatable in WPF. This is my first project in WPF. The datatable has a single column. The datatable is bound with a table that has a varbinary image column in database.
In database, this is the table structure

table tblPicture
@Picture varbinary(MAX)

it has 5 rows.

Datagrid gets filled with 5 rows (of datatype byte[]). But all the 5 rows are empty.

1) When page loads, the following code is executed:

public MainWindow()
Myclass cs = new Myclass ();
DataTable dt = cs.Method1();
this.dataGrid1.DataContext = dt;

2) The datagrid xaml code:

 <DataGrid AutoGenerateColumns="False" Height="650" Width="450" Name="dataGrid1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0" ItemsSource="{Binding}" CanUserAddRows="False">

                    <DataGridTemplateColumn IsReadOnly="True" Width="SizeToCells">
                        <Image Source="{Binding Path=Picture, Converter={StaticResource custom}}" Stretch="Fill" Height="100" Width="100" />

3) I have created this resource:

        <converters:BinaryImageConverter x:Key="custom"/>

<Window x:Class= ......

4) I have created the following converter class:

namespace WpfApplication2
    public class BinaryImageConverter : IValueConverter

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            if (value != null && value is byte[])
                byte[] bytes = value as byte[];

                MemoryStream stream = new MemoryStream(bytes);

                BitmapImage image = new BitmapImage();
                image.StreamSource = stream;
                return image;

            return null;

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            throw new Exception("The method or operation is not implemented.");

5) Method1 definition:

    public DataTable Method1()
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection("...");
        SqlDataAdapter sqlDa = new SqlDataAdapter("select Picture from tblPicture ", con);
        return dt;

Is this correct?
Can anyone please tell what i am missing? Are there any alternative solution for this

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.