Click here to Skip to main content
15,906,094 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I use WPF and C# in this project.
There is only an Insert button and a datagrid.
First I choose an image from datagrid,
then I press Insert button.
In my case when I press insert once, two images are inserted to my DB at the same time.
Where is the problem in my code?:

<window x:class="PupilReg.MainWindow" xmlns:x="#unknown">
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Image Insert" Height="674" Width="1009" WindowStartupLocation="CenterScreen" FontSize="15" FontWeight="Bold" ResizeMode="CanResizeWithGrip">
<grid margin="0,10,-8,-50">
<datagrid name="dataGrid1" height="565" width="435" margin="474,53,100,65">
<datagrid.itembindinggroup>
<bindinggroup>

<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" />





<Button x:Name="btnInsert" Content="Insert" HorizontalAlignment="Left" Margin="93,117,0,0" VerticalAlignment="Top" Width="75" Click="btnInsert_Click"/>



using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Windows;

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();
}
public void BindGrid1()
{
MySqlConnection con = new MySqlConnection(constr);
con.Open();
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 btnInsert_Click(object sender, RoutedEventArgs e)
{
DataRowView SelectedRowValue = (DataRowView)dataGrid1.SelectedValue;
byte[] ImageBytes = (byte[])SelectedRowValue.Row.ItemArray[1];
MySqlConnection con = new MySqlConnection(constr);
MySqlCommand cmd = new MySqlCommand("INSERT INTO images (Image_BLOB) VALUES (@ImageSource)", con);
cmd.Parameters.Add("@ImageSource", MySqlDbType.Blob, ImageBytes.Length).Value = ImageBytes;
con.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
cmd.ExecuteNonQuery();
MessageBox.Show("Image Inserted");
}
con.Close();
BindGrid1();
}
}
}
Posted

1 solution

Um...because you tell it to?
C#
int i = cmd.ExecuteNonQuery();
if (i > 0)
   {
   cmd.ExecuteNonQuery();
   MessageBox.Show("Image Inserted");
   }
Two calls to ExecuteNonQuery will give two INSERTs...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900