This tutorial will show you how to store images to database and bind to gridView. I have used FileUpload control to upload image from our computer and it’ll be stored to database as binary format and display these images to GridView.  

          First we have to create a table with three fields, ImageID, ImageName and Image. We need to store Image as binary format so we have to use varbinary() datatype.  


Store Image:

          Once we created our table then we have to design our ASPX page. First we have add TextBox control for image name, FileUpload control for image and Button to initiate upload.

     <div>

        <asp:TextBox ID="txtImageName" runat="server">

        </asp:TextBox>

        <asp:FileUpload ID="FileUpload1" runat="server" />

        <asp:Button ID="btnSubmit" runat="server" Text="Submit"      

                           OnClick="btnSubmit_Click" />

     </div>

 

Connection string:

            Here we have to add connection string to the web.config file

         <connectionStrings>

                   <add name="myConnectionString" connectionString="Data    

                     Source=localhost; Initial Catalog=Demo; User Id=sa;Password=sa123"/>

          </connectionStrings>

 

          On button click event we have to write following code to store image to database. Here we are going to convert image to binary format and it’ll be stored along with Image name. You will see that BinaryReader receives filestream to convert Image as binary data and it’ll be stored to byte array.

protected void btnSubmit_Click(object sender, EventArgs e)

    {

        try

        {

            Byte[] bytes = null;

            if (FileUpload1.HasFile)

            {

                string filename = FileUpload1.PostedFile.FileName;

                string filePath = Path.GetFileName(filename);

 

                Stream fs = FileUpload1.PostedFile.InputStream;

                BinaryReader br = new BinaryReader(fs);

                bytes = br.ReadBytes((Int32)fs.Length);

            }

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                SqlCommand command = new SqlCommand(

                 "INSERT INTO tblImage (ImageName, Image) " +

                 "Values(@ImageName, @Image)", connection); 

                command.Parameters.Add("@ImageName",

                SqlDbType.NVarChar, 20).Value = txtImageName.Text;

                command.Parameters.Add("@Image",

                SqlDbType.Binary).Value = bytes; 

                connection.Open();

                command.ExecuteNonQuery();

            }

        }

        catch (Exception)

        {     //error     }

    }

 

Retrieve Image:

          We have Image that has been stored to database as binary format. Now we are going to retrieve Image from database and we will display that to GridView. For that we have to add GridView Control to our .aspx page. In GridView we have to add BoundField for Image Name and TemplateField for Image. Then we have to create a Handler that will return Image from query string.  

GridView control look like this

         <asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false">

                <Columns>

                    <asp:BoundField DataField="ImageName" HeaderText="Image Name"/>

                    <asp:TemplateField HeaderText="Image">                   

                        <ItemTemplate>

                            <asp:Image ID="imgPreview" ImageUrl='<%#

                            "ImageHandler.ashx?imgID="+ Eval("ImageID") %>' runat="server"

                                Height="80px" Width="80px" />

                        </ItemTemplate>

                    </asp:TemplateField>

                </Columns>

            </asp:GridView>

 Bind GridView C# code:

protected void bindGrid()

    {

         DataSet ds = new DataSet();

         using (SqlConnection connection = new SqlConnection(connectionString))

         {

             connection.Open();

             string cmdstr = "Select ImageId, ImageName from tblImage";

             SqlCommand cmd = new SqlCommand(cmdstr, connection);

             SqlDataAdapter adp = new SqlDataAdapter(cmd);

             adp.Fill(ds);

             gvDetails.DataSource = ds;

             gvDetails.DataBind();

         } 

    }

Create Handler:

          Right click root folder -> Add New Item and add Generic Handler(ashx).


Now we have Handler file containing "ProcessRequest(HttpContext context)" method which gets triggered automatically.

public void ProcessRequest(HttpContext context)

    {      

            SqlDataReader rdr = null;

            SqlConnection conn = null;

            SqlCommand selcmd = null;

            try

            {

                conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);

                selcmd = new SqlCommand("select Image from tblImage where ImageID=" + context.Request.QueryString["imgID"], conn);

                conn.Open();

                rdr = selcmd.ExecuteReader();

                while (rdr.Read())

                {

                    context.Response.ContentType = "image/jpg";

                    context.Response.BinaryWrite((byte[])rdr["Image"]);

                }             

                rdr.Close();

            }

            finally

            {

                conn.Close();

            }  

}

 

I hope you understand how to store images to database and bind to GridView. You can download source code which is available along with this article.

Happy coding.. J  

cytotec abortion

an abortion pill buy abortion pills online
medical abortion pill online cytotec abortion abortion pill


View demo Download
http://www.dotnetfox.com/Document/1114/0photo1.jpg

If you enjoyed this article, get email updates (it's free).


Related Articles
  • File Upload in Gridview ASP.NETIn this article I’m going to explain how to use file upload control in grid view for uploading images or files to the server. The FileUpload control allows you to provide users with a way to send a file from their computer to the server. The control is useful for allowing users to upload images, text files or other files. Here I’ll show you how to use file upload control in gridview to upload the ...
  • Parse or read CSV file using TextFieldParser in ASP.NET CSV file contains multiple values which are separated by commas (,). In order to parse CSV file, we need to write some code. TextFieldParser class in the Microsoft.VisualBasic.FileIO namespace is used to parse CSV files. TextFieldParser reads in CSV files. With it, we specify a delimiter string, and then can read in the fields of every line in a loop. While parsing CSV file, it doesn’t fetch heade...
  • Store images to database and bind to GridView in ASP.NETThis tutorial will show you how to store images to database and bind to gridView. I have used FileUpload control to upload image from our computer and it’ll be stored to database as binary format and display these images to GridView. First we have to create a table with three fields, ImageID, ImageName and Image. We need to store Image as binary format so we have to use varbinary() datatype.
  • AJAX FileUpload or multiple FileUpload with progress example in ASP.NETThe AjaxFileUpload control is used to upload multiple files to the server folder. AjaxFileUpload uses one of two methods of showing file upload progress. If you are using a browser which fully supports the HTML5 File API (such as Google Chrome or Mozilla Firefox) then upload progress is displayed using client-side events. If, on the other hand, you are using a browser which does not fully support ...
  • Store and Retrieve Image from database in ASP.NETThis tutorial will show you how to store and retrieve image from database. I have used FileUpload control to upload image from our computer and it’ll be stored to database as binary format. First we have to create a table with three fields, ImageID, ImageName and Image. We need to store Image as binary format so we have to use varbinary() datatype.

Comments
comments powered by Disqus

Thanks for downloading..!!

×
Subscribe via Email
    
message to display in fancybox