Hi! I want retrieve photo from database by using datatable, because I need using datatable. By below code show error. Who is can help me by this method?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace Photo
{
public partial class Form1 : Form
{
public string dbPath = @"Data Source=localhost;Initial Catalog=infoDB;Integrated Security=True";
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
addInfo(txtLastName.Text.Trim(), txtName.Text.Trim(), picBox);
}
private void btnSearch_Click(object sender, EventArgs e)
{
DataTable dt = infoSearch(txtLastName.Text.Trim());
if (dt.Rows.Count > 0)
{
txtLastName.Text = dt.Rows[0]["LastName"].ToString();
txtName.Text = dt.Rows[0]["Name"].ToString();
byte[] bytes = (byte[])dt.Rows[0]["Photo"];
picBox.Image = Image.FromStream(new MemoryStream(bytes));
}
else
MessageBox.Show("Not found information!");
}
private void btnLoad_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Upload Employee Image...";
ofd.InitialDirectory = @"C:\";
ofd.Multiselect = false;
if (ofd.ShowDialog() != DialogResult.Cancel)
{
picBox.Image = Image.FromFile(ofd.FileName);
}
}
public void addInfo(string LastName, string Name, PictureBox Photo)
{
SqlConnection con = new SqlConnection(dbPath);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "insert into infoTable(LastName,Name,Photo)values('" + LastName + "','" + Name + "','" + Photo + "')";
con.Open();
try
{
cmd.ExecuteReader();
MessageBox.Show("CounterData successfully added", "SAVED - Fronty", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "Throwing Exception - Fronty", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
finally
{
con.Close();
}
}
public DataTable infoSearch(string LastName)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(dbPath);
SqlCommand cmd = con.CreateCommand();
DataSet dsd = new DataSet();
DataTable data = new DataTable();
cmd.CommandText = "select * from infoTable where LastName like '%" + LastName + "%'";
con.Open();
try
{
dt.Load(cmd.ExecuteReader());
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "Throwing Exception - Fronty", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
finally
{
con.Close();
}
return dt;
}
}
}
USE [infoDB]
GO
/****** Object: Table [dbo].[infoTable] Script Date: 07/10/2018 11:12:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[infoTable](
[Id] [int] IDENTITY(1,1) NOT NULL,
[LastName] [varchar](25) NULL,
[Name] [varchar](25) NULL,
[Photo] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO