Hi, droiddeve
I have created sample code which fullfill your requirement.
C#
public Form1()
{
InitializeComponent();
this.GetPics();
}
private void GetPics()
{
string constring = @"Data Source=.\SQL2005;Initial Catalog=Sample;User id = sa;password=pass@123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("select Data from tblFiles WHERE ContentType='jpg' ORDER BY ID DESC", con))
{
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult image = openFileDialog1.ShowDialog();
if (image == DialogResult.OK)
{
string filePath1 = openFileDialog1.FileName;
string filename = Path.GetFileName(filePath1);
FileStream fs = new FileStream(filePath1, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
string constring = @"Data Source=.\SQL2005;Initial Catalog=Sample;User id = sa;password=pass@123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO tblFiles VALUES(@Name,@ContentType,@Data) ", con))
{
cmd.Parameters.AddWithValue("@Name", filename);
cmd.Parameters.AddWithValue("@ContentType", "jpg");
cmd.Parameters.AddWithValue("@Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
this.GetPics();
}
}
Screenshot
