PictureBox taki Resimi
Sql Veritabanına Kaydedip DataGridView da Gösterimini Sağlamak
Merhaba arkadaşlar. Bu
makalemizde PictureBox ta gösterdiğimiz
image ları Sql veritabanına kaydedip, kaydedilen image ları DataGridView
nesnesinde göstereceğiz.
Formunuza OpenFileDialog,
PictureBox, Button ve DataGridView ekleyin.
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = "C:\\";
openFileDialog1.Filter = "All
Files|*.*|Bitmap|*.bmp|GIF|*.gif|JPEG|*.jpg";
openFileDialog1.FilterIndex = 4;
//PictureBox
a image ekliyoruz.
if
(openFileDialog1.ShowDialog() == DialogResult.OK) {
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.BorderStyle = BorderStyle.Fixed3D;
}
}
private void button2_Click(object sender, EventArgs e)
{
try {
SqlConnection baglan = new SqlConnection("Data
Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\bilgi.mdf;Integrated
Security=True;Connect Timeout=30");
SqlCommand cmd = new SqlCommand("INSERT INTO
[dbo].[Table](Id,Ad,Soyad,Resim) " + "VALUES (2 ,'Aydın','Akman', @Resim)", baglan);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] byteData = new byte[ms.Length];
ms.Position = 0;
ms.Read(byteData, 0, Convert.ToInt32(ms.Length));
//PictureBox
taki image ı byte olarak veritabanına ekliyoruz.
SqlParameter parametre = new SqlParameter("@Resim", SqlDbType.Image, byteData.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, byteData);
cmd.Parameters.Add(parametre);
baglan.Open();
cmd.ExecuteNonQuery();
baglan.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
SqlConnection baglan = new SqlConnection("Data
Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\bilgi.mdf;Integrated
Security=True;Connect Timeout=30");
SqlDataAdapter da = new SqlDataAdapter("Select Ad,Soyad,Resim
From [dbo].[Table]", baglan);
SqlCommand komut = new SqlCommand("Select Ad,Soyad,Resim
From [dbo].[Table]", baglan);
DataSet ds = new DataSet();
baglan.Open();
da.Fill(ds, "Table");
dataGridView1.DataSource =
ds.Tables[0];
baglan.Close();
}
}
}
Bir makalenin daha sonuna geldik. Bir sonraki makalede
görüşmek üzere. Bahadır ŞAHİN