Load picture from SQL database asp.net C#

odam2k

New Member
I have avatars stored in a database. I have used the the data type image for the avatars. I want to load the avatar of a user into an image control, but i cant get it to work. I have tried this code without any luck:\[code\]public void GetUserAvatar() { string username = Convert.ToString(Session["username"]); var image = from u in dc.Users where u.username == username select u.image; imgAvatar.Controls.Add(image); }\[/code\]I think i might have to save the images to a folder and then save the file path in the database instead. This seems to be easier and smoother. Any ideas?I ended up saving the image to a folder and then saving the path to the database. My code for image uploading now looks like this:\[code\]public void addImage() { if (fuAvatar.PostedFile.ContentType.ToLower().StartsWith ("image") && fuAvatar.HasFile) { string saveLocation = Server.MapPath("savedAvatars/"); string fileExtension = System.IO.Path.GetExtension(fuAvatar.FileName); string fileName = Convert.ToString(Session["userid"]); string savePath = saveLocation + fileName + fileExtension; fuAvatar.SaveAs(savePath); string imageDBPath = fileName + fileExtension; LinqClass1DataContext dc = new LinqClass1DataContext(); int userid = Convert.ToInt32(Session["userid"]); var tblUser = (from u in dc.Users where u.userid == userid select u).First(); tblUser.imagePath = @"\savedAvatars\"+imageDBPath; dc.SubmitChanges(); lblResult.Text = "Avatar lastet opp!"; } else lblResult.Text = "Avatar ikke lastet opp!"; }\[/code\]And to load the picture:\[code\]public void GetUserAvatar() { int userid = Convert.ToInt32(Session["userid"]); var varPath = dc.Users.Single(u => (u.userid == userid)).imagePath; string imagePath = Convert.ToString(varPath); imgAvatar.ImageUrl = imagePath; }\[/code\]
 
Top