Inserting Images To Database And Display in GridView

Previous article I explained about Displaying images From Database  Now we are discussing about how to insert image into database and display in the gridview

I am using fileupload Control to upload the image here we are saving the image path and the image is saved in the physical project Folder Hierarchy
Input Design Form look like



Here I am uploading the image name Employee.jpeg and Click on Submit button lets see how the code works.


Here I am using the Database table as follows:


In the Aspx Code Write the following Code:

<asp:GridView runat="server" ID="gvEmpdetails" DataKeyNames="ImageID" PageSize="5" AllowPaging="True"
AutoGenerateColumns="false" OnPageIndexChanging="gvEmpdetails_OnPageIndexChanging">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="ImageID" HeaderText="ImageID" SortExpression="ImageID" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="img" ImageUrl='<%# Eval("ImageURL")%>' Width="40px" Height="40px"
runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ImageDesc" HeaderText="ImageDescription" SortExpression="ImageDescription" />
</Columns>
</asp:GridView>
<table cellspacing="0" cellpadding="0" border="0" width="100%">
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td width="15%">
File Upload :
</td>
<td align="left">
<asp:FileUpload ID="fuimage" size="20" Width="34%" runat="server" />
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td width="15%">
Description :
</td>
<td align="left">
<asp:TextBox ID="txtDesc" runat="server" Width="23%" TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td width="15%">
</td>
<td align="left">
<asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClick="btnsubmit_OnClick" />
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
</table>



In the Code Behind Write the following Code:
In the Button Click event Check the Fileupload control is  True/False Then Proceed to
1) Finding the image size
2) Load the image
3) Assigning the physical path of image to the directorypath string variable
4) Condition to check drinfo exists or not
5) Assigning the image path to string serverpath
6) Save the imagepath in the local project 


public partial class InsertImageToDataBaseGridview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Binding Data From Database
            bindGridView();
        }
    }

    public void bindGridView()
    {
        //sql connection
        SqlConnection con = new SqlConnection("Data Source=TAPA-PC;user Id=sa;password=123;DataBase=Customer");
        SqlDataAdapter mySqlAdapter = new SqlDataAdapter("select ImageID, ImageURL,ImageDesc from Image ", con);
        DataSet myDataSet = new DataSet();
        mySqlAdapter.Fill(myDataSet);

        //Binding Data to gridview...
        gvEmpdetails.DataSource = myDataSet;
        gvEmpdetails.DataBind();

    }

    protected void gvEmpdetails_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvEmpdetails.PageIndex = e.NewPageIndex;
        bindGridView();
    }
    protected void btnsubmit_OnClick(object sender, EventArgs e)
    {
        if (fuimage.HasFile)
        {
            //finding the image size
            Byte[] bytes = fuimage.FileBytes;
            MemoryStream ms = new MemoryStream(bytes);

            //this statement is used to load the image
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);

            //Assigning the image filename to the imagename string
            string imagename = fuimage.FileName;
            //Assigning the physical path of image to the dirpath string
            string dirpath = System.Web.HttpContext.Current.Server.MapPath("Image\\");

            //Assigning the dirpath value to the directoryinfo
            DirectoryInfo drinfo = new DirectoryInfo("" + dirpath + "");

            //Condition to check drinfo exists or not
            if (!drinfo.Exists)
            {
                //it creates directory
                drinfo.Create();
            }

            //Assigning the image path to string serverpath
            string serverpath = dirpath + imagename;

            //Save the imagepath
            img.Save(serverpath);
            string dbpath = "~/Image" + "/" + imagename;

            //Update the image path by passing the Pout and dbpath value
            SqlConnection cn = new SqlConnection("Data Source=TAPA-PC;user Id=sa;password=123;DataBase=Customer");
            cn.Open();
            SqlCommand cmd = new SqlCommand("Img_InsertCommunity", cn);
            cmd.CommandType = CommandType.StoredProcedure;

            try
            {
                cmd.Parameters.AddWithValue("@ImageURL", dbpath);
                cmd.Parameters.AddWithValue("@ImageDesc", txtDesc.Text);

                int returnValue = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cmd.Dispose();
                cn.Close();
                cn.Dispose();
            }

        }
        bindGridView();
        txtDesc.Text = "";
    }
}




Out put  ScreenShots :
Employee.jpeg image is inserted to Database and loaded in the gridview as shown below




1 Responses to “Inserting Images To Database And Display in GridView”

Unknown said...
12 January 2013 at 21:57

how to display image which is saved outside the application dir?? for example image is saved by server in C:\users\desktop\1.jpg using fileupload control ,then how to save the path and display image in gridview without saving it to appliation dir... plz some one help .


Post a Comment

Labels

Topics