Home > ASP.Net > Set Default Image if user has no image in Database

Set Default Image if user has no image in Database


Hi

try this example:

In Page Load event try this code to check user image from database

if (!IsPostBack)
        {
            using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["cn"]))
            {
                string usr;
                // get user value from cookie, you may need to get it directly from sessio
                usr = Request.Cookies["user"].Value;
                // query to check if the user has image
                String cmdText = "SELECT image FROM photos where username='" + usr + "'";
                SqlCommand cmd = new SqlCommand(cmdText, cn);
                try
                {
                    cn.Open();
                    SqlDataReader rd = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                // if there is an image , set the imageUrl to the page that will render the user image from database (showimage.aspx)
                if (rd.HasRows)
                    Image1.ImageUrl = "showimage.aspx";
                // if there is no image for the user , set the image url to default image
                else
                    Image1.ImageUrl = "NullImage.jpg";
                }
                catch { Image1.ImageUrl = "NullImage.jpg"; }
                finally {
                    cn.Close();
                }    
            }
        }

Good Luck

Categories: ASP.Net
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment