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();
}
}
Related
I wanted to update my database that contains two text and one filename that is needed for image.
The problem is that the image and filename updates but the two other text values title and body wont be affected and don't change the previous values. Also visual studio don't get any problem and the message for executing command shows that it's executed the command but nothing except the image changes.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
Response.Redirect("~/default.aspx");
if (Request .QueryString ["action"]=="edit")
{
Panel1.Visible = true;
}
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString =GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString () + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text=myReader ["Title"].ToString ();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
protected void btn_addpost_Click(object sender, EventArgs e)
{
string title= title_txt .Text ;
string body=bodytxt .Text ;
if (Request.QueryString["edit"] != null)
{
string message;
string filename = thumb_uploader.FileName;
string path = HttpContext.Current.Server.MapPath("~") + "\\Thumb";
string exup = System.IO.Path.GetExtension(thumb_uploader.FileName);
string[] ext = { ".jpg", ".png", ".jpeg" };
if (Array.IndexOf(ext, exup) < 0)
{
message = "not correct.";
}
if (thumb_uploader.FileBytes.Length / 1024 > 400)
{
message = "not currect.";
}
while (System.IO.File.Exists(path + "\\" + filename + exup))
{
filename += "1";
}
savepath = path + "\\" + filename;
if (thumb_uploader.HasFile)
{
thumb_uploader.SaveAs(savepath);
thumb = thumb_uploader.FileName;
SqlCommand command;
SqlDataAdapter da;
SqlConnection con3 = new SqlConnection();
con3.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
command = new SqlCommand();
command.Connection = con3;
da = new SqlDataAdapter();
da.SelectCommand = command;
command.CommandText = "UPDATE tbl_post SET Title=#title ,Body=#body ,Thumb=#thu Where Postid=" + Request.QueryString["edit"].ToString();
con3.Open();
command.Parameters.AddWithValue("#title", title );
command.Parameters.AddWithValue("#body", body );
command.Parameters.AddWithValue("#thu", thumb_uploader .FileName);
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
else
{
using (SqlConnection con3 = new SqlConnection(GNews.Properties.Settings.Default.connectionstring))
{
string sql = "update tbl_post SET Title=#title ,Body=#body Where Postid=#postid" ;
using (SqlCommand command = new SqlCommand(sql, con3))
{
con3.Open();
command.Parameters.AddWithValue("#title", title);
command.Parameters.AddWithValue("#body", body);
command.Parameters.AddWithValue("#postid", Request.QueryString["edit"].ToString());
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
}
}
}
I've found the answer I needed this code to include my pageload reading database so it wouldn't do it when I click on the update button.I mean the problem was all about the post back thing.
if (!Page.IsPostBack)
{
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString() + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text = myReader["Title"].ToString();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
}
I am trying to use a LInklabel to open a hyperlink i have on my access database. However, this is the first time using a linklabel. Any suggestions would be great!
con.Open();
str = "Select * from loc where link ='" + facility+ "'";
cmd = new OleDbCommand(str, con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
linkLabel1.Text = dr.GetString(17);
}
The following code works for me:
private void Form1_Load(object sender, EventArgs e)
{
using (var con = new OleDbConnection())
{
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Public\Database1.accdb;";
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT FirstName, website FROM Clients WHERE ID = 1";
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Read();
String fName = rdr["FirstName"].ToString();
String url = rdr["website"].ToString();
if (url.Substring(0,1).Equals("#"))
{
// remove leading and trailing hash marks from URL
// as retrieved from a Hyperlink field in Access
url = url.Substring(1, url.Length - 2);
}
linkLabel1.Text = String.Format("Link to {0}'s website", fName);
linkLabel1.Links.Add(0, linkLabel1.Text.Length, url);
}
con.Close();
}
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string target = e.Link.LinkData as string;
System.Diagnostics.Process.Start(target);
}
I am doing a 3 tier application to retrieve image from sql server which i stored image to binary data in sql, and the problem is i can't retrieve my image from the sql server.
here is my code in DataAccessLayer
public List<Volunteer> VolunteerTRetrieve()
{
List<Volunteer> vList = new List<Volunteer>();
byte[] volunteerProfilePicture;
string volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact;
string queryStr = "SELECT * FROM TVolunteer Order By VolunteerName";
SqlConnection conn = new SqlConnection(DBconnStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while ((dr.Read()))
{
volunteerName = dr["VolunteerName"].ToString();
volunteerNRIC = dr["VolunteerNRIC"].ToString();
volunteerAddress = dr["VolunteerAddress"].ToString();
volunteerEmail = dr["VolunteerEmail"].ToString();
volunteerContact = dr["VolunteerContact"].ToString();
volunteerProfilePicture = (byte[])dr["VolunteerProfilePicture"];
vList.Add(new Volunteer(volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact, volunteerProfilePicture));
}
conn.Close();
dr.Dispose();
return vList;
}
in BusinessLogicLayer
public List<Volunteer> RetrieveAllBVolunteer()
{
Volunteer v = new Volunteer();
List<Volunteer> vList = new List<Volunteer>();
vList = v.VolunteerBRetrieve();
return vList;
}
and in PresentationLayer
List<Volunteer> allVolunteer = new List<Volunteer>();
allVolunteer = vBLL.RetrieveAllTVolunteer();
dl_tvolunteer.DataSource = allVolunteer;
dl_tvolunteer.DataBind();
I have also an image handler class
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["DBconnStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
string queryStr = "SELECT VolunteerProfilePicture FROM TVolunteer WHERE VolunteerNRIC = #NRIC";
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.Add("#NRIC", SqlDbType.VarChar).Value =
context.Request.QueryString["VolunteerNRIC"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["VolunteerProfilePicture"]);
}
Please help, Thankyou!
If you are returning one image you could the following
1. place a PictureBox control on the asp.net webpage
2. define the sql connections //not sure why you are using cmd.prepare
byte[] sqlImage = (byte[])cmd.ExecuteScalar();
MemoryStream memStream = new MemoryStream();
memStream.Write(sqlImage, 0, sqlImage.Length);
Bitmap bit = new Bitmap(memStream);
or if you want to do it a different way
try
{
con = new SqlConnection(constr);
cmd = new SqlCommand("select photopath,Photo from employees where employeeid=14", con);
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
if (!dr.IsDBNull(1))
{
byte[] photo = (byte[])dr[1];
MemoryStream ms = new MemoryStream(photo);
pictureBox1.Image = Image.FromStream(ms);
}
}
}
catch (Exception ex)
{
dr.Close();
cmd.Dispose();
con.Close();
Response.Write(ex.Message);
}
I would like to retrieve a particular column from a table when the values from two other columns are equal. My code is as follows. The four columns are id,destination,source,price.
I want to display the price when the destination and source are equal.
Could you please help me?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true");
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = new SqlCommand("select price from metro where source='" + textBox1.Text + "' and destination='" + textBox2.Text + "'", con);
da.Fill(dt);
for(int i=0;i<dt.Rows.Count;i++)
{
textBox3.Text = dt.Rows[0][3].Count.ToString();
}
}
I thing you are after this ....
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true"))
{
string query = "select price from metro where source= #Source and destination = #Destination";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Source", textBox1.Text);
cmd.Parameters.AddWithValue("#Destination", textBox2.Text);
con.Open();
object o = cmd.ExecuteScalar();
if(o != null && o != DBNull.Value)
{
string price = (string) o; //please cast the return type as required
textBox3.Text = price;
}
con.Close();
}
}
}
I have done this previously but in a different way. I am trying to get the code below to work. If I do not cast 'OriginalPhoto' or 'Thumbnail' an error occurs. Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. I don't understand why it asking to cast. However if I do cast it, the images add to the database just fine in a binary data format. When trying to view the images, i get the error 'Unable to display the given data'. I have inserted both byte[] into a table using a SqlDataAdapter and that works. I want to use this method though, what am I doing wrong?
PROFILEGALLERY TABLE CONTAINS:
UserId nvarchar(50)
Title nvarchar(10)
OriginalImage varbinary(max)
ThumbImage varbinary(max)
protected void AddPhotoToDatabase()
{
byte[] OriginalPhoto = GetImage();
byte[] Thumbnail = GenerateThumbnail();
string Title = FileUpload1.FileName.ToString();
string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES ('" + User.Identity.Name + "', '" + Title + "', CAST('" + OriginalPhoto + "'AS VARBINARY(MAX)), CAST('" + Thumbnail + "'AS VARBINARY(MAX)))";
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
protected byte[] GetImage()
{
byte[] photo = new byte[FileUpload1.PostedFile.ContentLength];
FileUpload1.PostedFile.InputStream.Read(photo, 0, photo.Length);
return photo;
}
protected byte[] GenerateThumbnail()
{
System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
double thumbwidth = 0;
double thumbheight = 0;
double imgsz = 150.0;
if (imgsz / image.Width < imgsz / image.Height)
{
thumbwidth = image.Width * (imgsz / image.Width);
thumbheight = image.Height * (imgsz / image.Width);
}
else
{
thumbwidth = image.Width * (imgsz / image.Height);
thumbheight = image.Height * (imgsz / image.Height);
}
System.Drawing.Image thumb = image.GetThumbnailImage((int)thumbwidth, (int)thumbheight, delegate() { return false; }, (IntPtr)0);
MemoryStream ms = new MemoryStream();
thumb.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
You should use sql parameters:
using( SqlConnection cnn = GetConnection() ) {
using( SqlCommand cmd = cnn.CreateCommand() ) {
cmd.CommandText = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES (#UserId, #Title, #OriginalPhoto, #Thumbnail)";
cmd.Parameters.AddWithValue( "#UserId", User.Identity.Name );
cmd.Parameters.AddWithValue( "#Title", Title );
cmd.Parameters.AddWithValue( "#OriginalPhoto", OriginalPhoto );
cmd.Parameters.AddWithValue( "#Thumbnail", Thumbnail );
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
}
}
Don't try to build the data into the insert query. Try this:
string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage],
[ThumbImage]) VALUES (#userId, #title, #originalImage, #thumbImage)";
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
comm.Parameters.Add(new SqlParameter("#userId", User.Identity.Name));
comm.Parameters.Add(new SqlParameter("#title", Title));
comm.Parameters.Add(new SqlParameter("#originalImage", OriginalPhoto));
comm.Parameters.Add(new SqlParameter("#thumbImage", Thumbnail));
Just looking at your code, I'm a little concerned that you are wide open for a SQL Injection attack. To help mitigate this should also fix your problem. You need to use a parametized query. Something like
cmd.CommandText="Insert into [ProfileGallery]" +
"(UserId,OriginalPhoto) values (#UserId,#OriginalPhoto)";
cmd.Parameters.AddWithValue("UserId",User.Identity.Name);
cmd.Parameters.AddWithValue("OriginalPhoto",OriginalPhoto);
The reason your code is failing can be seen with this sample application:
static void Main(string[] args)
{
byte[] byteArray = new byte[] { 1, 2, 0 };
Console.WriteLine("This is my byte array: " + byteArray);
Console.ReadLine();
}
This outputs This is my byte array: System.Byte[]
I'm a little shocked that you can add a byte array to a string, especially sicne it just gives us the name of the type.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
SqlConnection cn = new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
string strSQL = "Select * from table6";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, cn);
DataSet ds = new DataSet();
dt.Fill(ds);
grd1.DataSource = ds;
grd1.DataBind();
cn.Close();
}
protected void btn1_Click(object sender, EventArgs e)
{
if(fileupload.HasFile)
{
string imageSrc = "~/Image/" +fileupload.PostedFile.FileName;
string ImageName = txt1.Text;
SqlConnection cn=new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
cn.Open();
string strSql = "Insert Into table6 (ImageName,Image) values ('" + ImageName + "','"+imageSrc+"')";
SqlCommand cmd = new SqlCommand(strSql, cn);
cmd.ExecuteNonQuery();
cn.Close();
BindData();
txt1.Text = "";
}
This simple code is enough to insert images to SQL without taking HTTP Handler
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
SqlConnection cn = new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
string strSQL = "Select * from table6";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, cn);
DataSet ds = new DataSet();
dt.Fill(ds);
grd1.DataSource = ds;
grd1.DataBind();
cn.Close();
}
protected void btn1_Click(object sender, EventArgs e)
{
if(fileupload.HasFile)
{
string imageSrc = "~/Image/" +fileupload.PostedFile.FileName;
string ImageName = txt1.Text;
SqlConnection cn=new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
cn.Open();
string strSql = "Insert Into table6 (ImageName,Image) values ('" + ImageName + "','"+imageSrc+"')";
SqlCommand cmd = new SqlCommand(strSql, cn);
cmd.ExecuteNonQuery();
cn.Close();
BindData();
txt1.Text = "";
}