Loading Image through label - c#

I am trying to load an image through label using this code
private void getData()
{
SqlConnection conn = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
conn.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT empName,empLname,empMi,empImage
FROM employees
WHERE empName = '"+ ddlAvail.SelectedItem.Value.ToString() +"'", conn);
SqlDataReader rdr = sqlCmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
lblName.Text = rdr.GetValue(0).ToString();
lblLname.Text = rdr.GetValue(1).ToString();
lblMi.Text = rdr.GetValue(2).ToString();
lblImage.Text = "<img runat='server' src='" + rdr.GetValue(3).ToString() + "'></img>";
}
}
conn.Close();
}
every time I select a dropdownlist value it generates me set of sql data.My only problem is the image.Cause it wont load any image at all.The filepath on my visual studio and image name is correct.
This is an example of my image
../Images/Profile/logo.jpg
I save the images filepath on my database.

Your code looks fine
Make sure the file path your are retrieving from the database exists and the path isn't returning any unwanted characters.
That is:
rdr.GetValue(3).ToString() //should return the right path (string)
It should be fine. Hope this helped

It won't ever show the image because all that your code is doing is setting the text on the label.
If you want to display the image try this , or this.

Related

Updating and retrieving images (Asp.net c#)

protected void upimg_about_Click(object sender, EventArgs e)
{
con.Open();
string sqlQuery = " UPDATE [dbo].[tbldetails] SET [image]=#image,[image2]=#image2 WHERE id=#id";
SqlCommand cmd2 = new SqlCommand(sqlQuery, con);
cmd2.Parameters.AddWithValue("#id", Session["email"].ToString());
int img = Image1.PostedFile.ContentLength;
int img2 = Image2.PostedFile.ContentLength;
byte[] msdata = new byte[img];
byte[] msdata2 = new byte[img2];
Image1.PostedFile.InputStream.Read(msdata, 0, img);
Image2.PostedFile.InputStream.Read(msdata2, 0, img2);
cmd2.Parameters.AddWithValue("#image", msdata);
cmd2.Parameters.AddWithValue("#image2", msdata2);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd2.ExecuteNonQuery();
con.Close();
data1.Text="Image Updated Successfully";
}
This is the code I am using to update the images in the database.
The user when required can update the images (eg: in the firstpage.aspx) and can retrieve it in the next page (nextpage.aspx).
But the problem is: suppose a user wants to update just a single image and he/she upload's the image and clicks the update button and when retrieving images in the next page the image that was updated is visible but the one which is already present in the database is not. I am not sure but during the updation the other fileupload is empty is this why this is happening? Is there other way to do it?
PS: I have textboxes in the firstpage.aspx in which i am retrieving the text he/she has already put in the database and hence when the user wants to make changes it can be done easily.
TextBox1.Text = dr["name"].ToString();
TextBox2.Text = dr["address"].ToString();
So, is it possible to retrieve the image path which the user has previously submitted? Or any way in which the user can update a single image and during retrieval both the images can be retrieved?
Thank You! :)
Break your code up so that you can send 1 image at a time to the DB. Then pass the corresponding FileUpload and SQL Column name to your function. Conditionally send the new file to the database depending on whether the FileUpload contains a file. You can check this by looking at the HasFile property.
protected void upimg_about_Click(object sender, EventArgs e)
{
// make sure at least 1 file
if (!Image1.HasFile && !Image2.HasFile)
{
data1.Text="No Images Uploaded";
return;
}
con.Open();
UploadImage(Image1, "[image]");
UploadImage(Image2, "[image2]");
con.Close();
data1.Text = "Image Updated Successfully";
}
void UploadImage(FileUpload fileUpload, string columnName)
{
if (!fileUpload.HasFile)
{
return;
}
string sqlQuery = "UPDATE [dbo].[tbldetails] SET " + columnName + "=#image WHERE id=#id";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.AddWithValue("#id", Session["email"].ToString());
int img = fileUpload.PostedFile.ContentLength;
byte[] msdata = new byte[img];
fileUpload.PostedFile.InputStream.Read(msdata, 0, img);
cmd.Parameters.AddWithValue("#image", msdata);
cmd.ExecuteNonQuery();
}

Binding SQL data to Label in WPF

Is there a way to data bind SQL data to a label in WPF?
I have a SQL database that has a total of summed up data. I want to display the last column's data to a label. So if the column reads "10" then I need the label to display "10".
Here is the code I've tried:
C#:
SqlConnection con = new SqlConnection(myconnectioninfo);
SqlCommand scom = new SqlCommand();
scom.CommandText = "SELECT TOP 1 [TotalIncidents] FROM sixMonthReport ORDER BY [TotalIncidents] DESC"
Object temp = cmd.ExecuteScalar();
label.Text = temp.ToString();
Most appeared to work until I get to the label.text portion which is not an option in WPF.
I can't seem to find any information on much of WPF / labels any help is appreciated.
label does not have a text property but it does have content one, so you can try something like:
Object temp = null;
using (SqlConnection con = new SqlConnection(myconnectioninfo))
{
con.Open();
using (SqlCommand command = new SqlCommand("SELECT TOP 1 [TotalIncidents] FROM sixMonthReport ORDER BY [TotalIncidents] DESC", con))
{
temp = cmd.ExecuteScalar();
}
}
label.Content = temp?.ToString();

Delete the old image when it has to upload new image

this is so that when I need to upload a right an image to an article so it must delete the old image
and it must be clear in the folder where the image is located,
string Tid = DateTime.Now.Ticks.ToString();
string unikID = Guid.NewGuid().ToString();
string url = "~/img/bimg/";
cmd.CommandText = "SELECT img FROM aktiviteter WHERE Id = #id;";
cmd.Parameters.AddWithValue("#Id", id);
conn.Open();
SqlDataReader readerImg = cmd.ExecuteReader();
if (readerImg.Read())
{
File.Delete(Server.MapPath(url.Remove(0, 1) + readerImg["img"]));
}
conn.Close();
problem is that I need to find the image in the column in the database where the entity who should delete the picture
Access to the path 'C:\Users\198407\Documents\Visual Studio 2013\WebSites\Jesper-mm-CRUD\img\bimg\' is denied.
my pictures located here: /img/bimg/hello.png
how it looks when I load to the server
string Tid = DateTime.Now.Ticks.ToString();
string unikID = Guid.NewGuid().ToString();
string url = "~/img/bimg/";
cmd.CommandText = "SELECT img FROM aktiviteter WHERE Id = #id;";
cmd.Parameters.AddWithValue("#Id", id);
conn.Open();
SqlDataReader readerImg = cmd.ExecuteReader();
if (readerImg.Read())
{
File.Delete(Server.MapPath(url.Remove(0, 1) + readerImg["img"]));
}
conn.Close();
ImageNet.FluentImage img = ImageNet.FluentImage.FromStream(FileUploadImg.FileContent);
img.Resize.Scale(360).Save(Server.MapPath(url + unikID + ".png"));
if (File.Exists(Server.MapPath(url + unikID + ".png")))
{
cmd.CommandText = "UPDATE aktiviteter SET navn = #navn, sted = #sted, indhold = #indhold, img = #img, rubrik = #rubrik, retbrugerID = #retbrugerid WHERE Id = #id;";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#navn", navn);
cmd.Parameters.AddWithValue("#sted", Sted);
cmd.Parameters.AddWithValue("#indhold", Indhold);
cmd.Parameters.AddWithValue("#img", unikID);
cmd.Parameters.AddWithValue("#rubrik", rubrik);
cmd.Parameters.AddWithValue("#retbrugerid", brugerid);
}
Since you are getting this error -
Access to the path 'C:\Users\198407\Documents\Visual Studio
2013\WebSites\Jesper-mm-CRUD\img\bimg\' is denied.
I would suggest , granting read/write access to this user = IIS_IUSRS for required directory.
Read more helpful link

Not getting image in Image Control by Url in asp.net

Hello Friends i am storing an image via URL in database but when i retrieve it on Image Control of asp.net it doesn't show the image please help
Profile.aspx.cs
con.Open();
string str = "SELECT * FROM [aspdotnetpractice].[dbo].[Users] where Username ='" + lblHowdy.Text + "'";
SqlCommand com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
Image1.ImageUrl = Server.MapPath(reader[8].ToString());
Label1.Text = reader[1].ToString();
Label2.Text = reader[2].ToString();
Label3.Text = reader[3].ToString();
Label4.Text = reader[6].ToString();
Label5.Text = reader[4].ToString();
reader.Close();
con.Close();
}
Make sure you save path value like "ImageFiles/test.jpg" or filename only like "test.jpg". Dont save to path field a complete local path like "c:\…\test.jpg". In imageurl you should use virtual path instead physical path.
The Server.MapPath returns a file name. On the other hand, Image.ResolveUrl expects a valid url.
You'd rather want something like
Image1.ImageUrl = Page.ResolveUrl("~/ImageFiles/") + fi.Name; // You just need to pass name or something similar.

upload new file first check if this file exist already in database or not then if not exist save that in database

I'm trying to create sql database that contains
Image Id (int)
Imagename (varchar(50))
Image (image)
and in aspx write in upload button this code:
protected void btnUpload_Click(object sender, EventArgs e)
{
//Condition to check if the file uploaded or not
if (fileuploadImage.HasFile)
{
//getting length of uploaded file
int length = fileuploadImage.PostedFile.ContentLength;
//create a byte array to store the binary image data
byte[] imgbyte = new byte[length];
//store the currently selected file in memeory
HttpPostedFile img = fileuploadImage.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length);
string imagename = txtImageName.Text;
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)", connection);
cmd.Parameters.Add("#imagename", SqlDbType.VarChar, 50).Value = imagename;
cmd.Parameters.Add("#imagedata", SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
BindGridData();
txtImageName.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
When I'm uploading a new image I need to first check if this image already exists in database and if it doesn't exist save that in database.
Please how I can do that?
Add a method that is responsible for checking if the filename already exists in the table.
private bool FileExists(string imageName)
{
using (SqlConnection conn = new SqlConnection()) // establish connection
{
using (SqlCommand cmd =
new SqlCommand("select 1 where exists(select Id from Image where ImageName = #)", conn))
{
cmd.Parameters.Add("#imagename", SqlDbType.VarChar, 50).Value = imageName;
return cmd.ExecuteNonQuery() > 0;
}
}
}
Then I would call this like so
if (fileuploadImage.HasFile && !FileExists(txtImageName.Text))
{
...
string cmd ="if not exists (select * from Image where ImageName= #imagename); ";
\\if you want to check image data
\\ (select * from Image where SUBSTRING(ImageName, 1, 8000)= SUBSTRING(#imagename, 1, 8000) );
string cmd += "INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)";
SqlCommand cmd = new SqlCommand(cmd, connection);
If you want to verify imagedata, You can try to use DATALENGTH as first line of check for the two images.
If the DATALENGTH is different, then you suppose to have a "different" picture".
You can also use SUBSTRING(Image, 1, 8000) to check first 8000 bytes.
And also SUBSTRING(Image, DATALENGTH(Image) - 7999, 8000) to check last 8000 bytes.
One of the fastest ways is to do an UPDATE and then INSERT if update returns no updates.
string cmd = #"UPDATE Image SET Image = #imagedata WHERE ImageName = #ImageName
IF ##ROWCOUNT=0
INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)";
Or if query on Image itself:
string cmd = #"UPDATE Image SET ImageName = #ImageName WHERE Image = #imagedata
IF ##ROWCOUNT=0
INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)";

Categories

Resources