Hi,
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()
{
InitializeComponent();
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">
<DataGrid.Columns>
<DataGridTemplateColumn IsReadOnly="True" Width="SizeToCells">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Path=Picture, Converter={StaticResource custom}}" Stretch="Fill" Height="100" Width="100" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
3) I have created this resource:
<Window.Resources>
<converters:BinaryImageConverter x:Key="custom"/>
</Window.Resources>
<Window x:Class= ......
xmlns:converters="clr-namespace:WpfApplication2"
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.BeginInit();
image.StreamSource = stream;
image.EndInit();
System.Diagnostics.Debugger.Break();
return image;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
System.Diagnostics.Debugger.Break();
throw new Exception("The method or operation is not implemented.");
}
}
}
5) Method1 definition:
public DataTable Method1()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection("...");
con.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("select Picture from tblPicture ", con);
sqlDa.Fill(dt);
con.Close();
return dt;
}
Is this correct?
Can anyone please tell what i am missing? Are there any alternative solution for this