我的图像插入事件有问题。 图像数据类型是blob。 问题领域是:
"byte[] ImageBytes = (byte[])SelectedRowValue.Row.ItemArray[0];"
错误消息说:
"Unable to cast object of type 'System.Int32' to type 'System.Byte[]'."
下面是我的xaml,c#和sql代码。它们被删节并简化了我真实项目的一部分:
XAML项目只包含一个按钮和一个数据网格
<Window x:Class="PupilReg.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Binding To Ado.net" Height="644.351" Width="674.234" FontSize="15" FontWeight="Bold" ResizeMode="CanResizeWithGrip">
<Grid>
<DataGrid Name="dataGrid1" Height="565" Width="435" AutoGenerateColumns="False" Margin="188,10,43,38">
<DataGrid.ItemBindingGroup>
<BindingGroup/>
</DataGrid.ItemBindingGroup>
<DataGrid.Columns>
<DataGridTextColumn Header="Image_ID" Binding="{Binding Path=Image_ID}" Width="80"/>
<DataGridTemplateColumn Header="Image_BLOB" Width="200" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Path=Image_BLOB}" Width="160" Height="160" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="InsertImage" Content="Insert" Click="InsertImage_Click" Margin="31,39,583,541"/>
</Grid>
C#
namespace PupilReg
{
public partial class MainWindow : Window
{
string constr = "Data Source=localhost;port=3306;Initial Catalog=test;User Id=root;password=2525";
public MainWindow()
{
InitializeComponent();
BindGrid1();
}
private void BindGrid1()
{
MySqlConnection con = new MySqlConnection(constr);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM images", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGrid1.ItemsSource = dt.DefaultView;
}
private void InsertImage_Click(object sender, RoutedEventArgs e)
{
{
DataRowView SelectedRowValue = (DataRowView)dataGrid1.SelectedValue;
byte[] ImageBytes = (byte [])SelectedRowValue.Row.ItemArray[0];
MySqlConnection objConnection = new MySqlConnection (constr);
string CommandText = "INSERT INTO images (Image) VALUES (@ImageSource)";
MySqlCommand objCommand = new MySqlCommand(CommandText, objConnection);
objCommand.Parameters.Add("@ImageSource", MySqlDbType.Blob, ImageBytes.Length).Value = ImageBytes;
objConnection.Open();
objCommand.ExecuteNonQuery();
objConnection.Close();
}
}
}
}
SQL
CREATE TABLE `images`
(
`Image_ID` int(32) NOT NULL AUTO_INCREMENT,
`Image_BLOB` blob,
PRIMARY KEY (`Image_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=binary;