displaying images on crystalreport - c#

This is my code,i want display images that stored in sql to crystal reports,please someone help me :)
private void button2_Click(object sender, EventArgs e)
{
string connectionstring = null;
SqlConnection conn;
connectionstring="Server=AJITHBABU\\SQLEXPRESS;Initial Catalog=temprorary;User ID=sa;Password=2604";
conn=new SqlConnection(connectionstring);
byte[] img = null;
FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
k = "INSERT INTO temprorary4(id,img)values('" + textBox1.Text + "',#img)";
conn.Open();
cmd = new SqlCommand(k, conn);
cmd.Parameters.Add(new SqlParameter("#img",img));
int x=cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show(x.ToString() +"record(s) saved");
}

Related

Trying to upload image file to database using input from asp.net page getting error

I am trying to upload an image to a mysql database. I upload the image on a asp.net page . But i am getting this error whenever i try to upload the image to the database.
System.FormatException: 'Input string was not in a correct format.'
on the line with this code
MySqlDataReader MyReader2 = MyCommand2.ExecuteReader();
This is the complete code that i tried
protected void upload_files(object sender, EventArgs e)
{
if (FileUpload_UploadFile.HasFile)
{
HttpPostedFile img = FileUpload_UploadFile.PostedFile;
// IMPLEMENT YOUR CODE FOR SAVING THE FILE
Console.Write(img);
Stream stream = img.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
bytes = binaryReader.ReadBytes((int)stream.Length);
result = System.Text.Encoding.UTF8.GetString(bytes);
myLabel2.Text = "file has been uploaded";
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sql_command = "Insert INTO Recognized_person1 (Name,Image,Department,Department_id) VALUES (#Name, #Image, #Department, #Department_id )";
conn.Open();
MySqlCommand MyCommand2 = new MySqlCommand(sql_command, conn);
MyCommand2.Parameters.AddWithValue("#Name", MySqlDbType.VarChar).Value = Name.Text;
MyCommand2.Parameters.AddWithValue("#Image", MySqlDbType.Blob).Value = bytes;
MyCommand2.Parameters.AddWithValue("#Department", MySqlDbType.VarChar).Value = Department.Text ;
MyCommand2.Parameters.AddWithValue("#Department_id", MySqlDbType.Int32).Value = Int32.Parse((Department_id1.Text));
//MyCommand2.ExecuteNonQuery();
MySqlDataReader MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
}
conn.Close();
}
}
Any ideas on how to correct this error ?

"Parameter is not valid" error when retrieving image

I want to retrieve images from a SQL Server database using C#. However, I'm getting the error message
Parameter is not valid
Please help me.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string q = "select * from Rough where name='" + comboBox1.Text + "'";
SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=SMS_DB;Integrated Security=True");
SqlCommand cmd = new SqlCommand(q, con);
SqlDataReader dr;
if (con.State == ConnectionState.Closed)
{
con.Open();
dr = cmd.ExecuteReader();
byte[] img = null;
while (dr.Read())
{
textBox1.Text = (dr["ID"].ToString());
textBox2.Text = (dr["Name"].ToString());
textBox3.Text = (dr["Image"].ToString());
img = (byte[])(dr["Image"]);
if (img == null)
{
pictureBox2.Image = null;
}
else
{
MemoryStream ms = new MemoryStream(img);
pictureBox2.Image = Image.FromStream(ms);
// ms.Close();
}
}
con.Close();
}
}

Replacing an image in a database with c# (using UPDATE)

I have a database with images stored in it and I want to replace those images with new ones. Here is the thing: I have a picturebox and in this picturebox I am downloading an image. This image is the one that I want to use to replace the current image of my databaserow where my column "Id" is 6.
Right now I am trying to do it with UPDATE but it is not working and I am wondering why. Here is my code:
private void buttonReplace_Click(object sender, EventArgs e)
{
string sql = "SELECT * FROM [Insert_Image]"; //name of database
SqlDataAdapter dA = new SqlDataAdapter(sql, cn);
DataTable dT = new DataTable();
dA.Fill(dT);
int z = dT.Rows.Count + 1;
int i = 6;
try
{
cn.Open();
byte[] img = null;
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string strSql = "UPDATE [Insert_Image] SET Picture = " + #img + " WHERE Id LIKE '" + i + "'";
SqlCommand cmd = new SqlCommand(strSql, cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(Convert.ToString(ex));
}
finally
{
cn.Close();
}
}
My Problem is that something is saved in my database, but whatever I am saving with this code is not the binary-code for an image. I checked my filestream and that is correct as I am using the same filestream I used for uploading to the picturebox. I would be very glad for any help or ideas.
do not hard code value in the query, instead use.
cmd.Parameters.Addnew SqlParameter("#img", img));
check this cheet sheet on SQL Injection
string strSql = "UPDATE [tablename] SET Picture=#img WHERE Id LIKE '%#i%'";
SqlCommand cmd = new SqlCommand(strSql, cn);
cmd.Parameters.Add(new SqlParameter("#img", img));
cmd.Parameters.Add(new SqlParameter("#i", i));
cmd.ExecuteNonQuery();

Datagridview cell mouseClick event error

can you help me to this problem
i have one form production from where i can upload that photo and save it on to the database,
but when i do a cellmouseclick event it having some problem
and below is the code for doing so:
SqlConnection con = new SqlConnection("Data Source=ANTONIANGGA-PC\\SQLEXPRESS;Initial Catalog=FullandStarving;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
SqlDataReader dr;
private void button2_Click(object sender, EventArgs e)
{
byte[] image = null;
FileStream fs = new FileStream(this.txtLink.Text, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
image = br.ReadBytes ((int)fs.Length);
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto,Photo) Values(#IDProduksi,#IDPhoto,#TanggalProduksi,#NamaKaryawan,#KeteranganPhoto,#Photo)", con);
cmd.Parameters.AddWithValue("#IDProduksi", txtIdpro.Text);
cmd.Parameters.AddWithValue("#IDPhoto", txtIdPhoto.Text);
cmd.Parameters.AddWithValue("#TanggalProduksi", dProduksi);
cmd.Parameters.AddWithValue("#NamaKaryawan", txtNamaKaryawan.Text);
cmd.Parameters.AddWithValue("#KeteranganPhoto", rxtKtrphoto.Text);
cmd.Parameters.AddWithValue("#Photo", image);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
con.Close();
showgridview();
clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
txtIdpro.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
txtIdPhoto.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
dtmProduksi.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
txtNamaKaryawan.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
rxtKtrphoto.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString();
txtLink.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString();
// wanna show that picture when you klik cell
byte[] imgg = (byte[])(dr["Photo"]);
MemoryStream Strem = new MemoryStream(imgg);
pictureBox1.Image = System.Drawing.Image.FromStream(Strem);
}
and if i commend that byte[] that can be like that below :
and if i commend that byte[] that can be like that below :
You need to initialize dr. You must create in dataGridView1_CellMouseClick a select query and than you can do this:
dr = cmd.ExecuteReader();
while (dr.Read()) { }

Insert and Update Image in sql

I am storing images to the database in the table test (id, name, image), by reading images from a picture box.
This is my code:
private void browse_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "(*.BMP;*.JPG;*.GIF;*.JPEG;*.PNG)|*.BMP;*.JPG;*.GIF;*.JPEG;*.PNG";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
imgloc = openFileDialog1.FileName.ToString();
pictureBox1.ImageLocation = imgloc;
}
}
private void save_Click(object sender, EventArgs e)
{
byte[] img = null;
FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
SqlConnection CN = new SqlConnection(constring);
string Query = "insert into test (id,name,image) values('" + txtid.Text + "','" + txtname.Text + "',#img)";
CN.Open();
cmd = new SqlCommand(Query, CN);
cmd.Parameters.Add(new SqlParameter("#img", img));
cmd.ExecuteNonQuery();
CN.Close();
}
It works but I would like to know how to use the update command here.
private void update_Click(object sender, EventArgs e)
{
byte[] img = null;
FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
SqlConnection CN = new SqlConnection(constring);
// this is a smaple query for update statement and update where id=#id
string Query = "update test set name=#name,image=#img where id=#id ";
CN.Open();
cmd = new SqlCommand(Query, CN);
cmd.Parameters.Add(new SqlParameter("#img", img));
cmd.Parameters.Add(new SqlParameter("#id", txtid.Text));
cmd.Parameters.Add(new SqlParameter("#name", txtname.Text));
cmd.ExecuteNonQuery();
CN.Close();
}
Your code and query should be like this :
SqlConnection CN = new SqlConnection(constring);
string Query = "Update test Set name=#Name,image=#Image where id=#id"
CN.Open();
cmd = new SqlCommand(Query, CN);
cmd.Parameters.Add(new SqlParameter("#Image", img));
cmd.Parameters.Add(new SqlParameter("#Name",txtname.Text));
cmd.Parameters.Add(new SqlParameter("#id",txtid.Text));
cmd.ExecuteNonQuery();
CN.Close();
Just delete that particular record using your Id field and Fire the Save query again, if updating is difficult.
SqlConnection con = Connectionclass.SQLCONNECTION();
SqlDataAdapter da = new SqlDataAdapter();
string query = ("Update Doctor set ID ='" + idtxt.Text + "',Name='" + nametxt.Text + "',Contact='" + contactxt.Text + "',CNIC='" + cnictxt.Text + "',Address='" + addresstxt.Text + "',Qualification='" + qualitxt.Text + "',specialization='" + specialtxt.Text + "',Gender='" + gendertxt.Text + "',DOB='" + dobtxt.Text + "', Fee='"+textBox1.Text+"',Date='" + System.DateTime.Today.ToString("dd-MM-yyyy") + "', Picture= #image where ID='" + idtxt.Text + "'");
da.UpdateCommand = new SqlCommand(query, con);
con.Open();
da.UpdateCommand.Parameters.Add("image", SqlDbType.VarBinary).Value = binaryphoto;
int RowsEffected = da.UpdateCommand.ExecuteNonQuery();
con.Close();

Categories

Resources