How to store and retrieve Image in Database using C# ASP.Net jQuery

In this article, I’ll explain how to store and retrieve Image in Database using C# ASP.Net jQuery. There is many other way to do that but here is the easiest way to do it.
Database:
For this tutorial, I am using following database.

CREATE TABLE [dbo].[tblImage](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[image] [image] NULL,
 CONSTRAINT [PK_tblImage] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

Connection string:
Below is the connection string to connect to the database.

<connectionStrings>
    <add name="TempConnectionString" connectionString="Data Source=ASHISH;Initial Catalog=Temp;Persist Security Info=True;User ID=sa;Password=Temp1234567" providerName="System.Data.SqlClient"/>
</connectionStrings>

Page:
In this tutorial, there one aspx page and one handler.
1. UploadImage.aspx – To Store image into database
2. DisplayImage.aspx – To display image from handler
3. DisplayImage.ashx – To read image from database (Handler)

1. UploadImage.aspx
Upload image
Below HTML Markup of the page, you will notice that I have placed FileUpload to upload image into database.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadImge.aspx.cs" Inherits="UploadImge" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Ashish Blog</title>
</head>
<body>
    <form id="form1" runat="server">
    <strong>Upload Image into database</strong><br />
    <br />
    Select
Image: <asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="butSubmit" runat="server" Text="Submit"
onclick="butSubmit_Click" /><br />
<asp:Label ID="lblStatus" runat="server"></asp:Label>
   <br />
    <br />
    <a href="DisplayImage.aspx">Display Image</a></form>
</body>
</html>

Codebehind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class UploadImge : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void butSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            Byte[] imgByte = null;
            if (FileUpload1.HasFile &amp;&amp; FileUpload1.PostedFile != null)
            {
                HttpPostedFile File = FileUpload1.PostedFile;
                imgByte = new Byte[File.ContentLength];
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            }
            string cs = ConfigurationManager.ConnectionStrings["TempConnectionString"].ConnectionString;
           using( SqlConnection connection = new SqlConnection(cs))
           {
               connection.Open();
               string sql = "INSERT INTO tblImage(image) VALUES(@theImage) SELECT @@IDENTITY";
               using (SqlCommand cmd = new SqlCommand(sql, connection))
               {
                   cmd.Parameters.AddWithValue("@theImage", imgByte);
                   int id = Convert.ToInt32(cmd.ExecuteScalar());
                   lblStatus.Text = String.Format("Image is Uploaded successfully!! and Image ID is {0}", id);
                   cmd.Dispose();
               }
               connection.Close();
               connection.Dispose();
           }
        }
        catch(Exception ex)
        {
            lblStatus.Text = "There was an error" + ex.Message ;
        }
       
    }
}

2. DisplayImage.aspx
display image
Below HTML Markup of the page, you will notice that I have placed jQuery function to display Image from database. You may also notice that I created Img variable and call ReadImage.ashx handler by passing Image ID in scr attribute of Img then append this Img to div.display.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DisplayImage.aspx.cs" Inherits="DisplayImage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#Button1").click(function (e) {
                $('.display').text('');   //clean div display
                var ID = $("#txtID").val();
                if (ID.length > 0) {
                    var newImage = $('<img />');
                    newImage.attr('src', 'ReadImage.ashx?id=' + ID); // call handler with id
                    $('.display').append(newImage);
                }
                e.preventDefault();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
     Display Image<br />
    <br />
    Id
    <asp:TextBox ID="txtID" runat="server"></asp:TextBox>
&amp;amp;nbsp;<asp:Button ID="Button1" runat="server" Text="Display" />
    <br />
    <br />
    <div class="display"></div>
    <br />
    <br />
    </form>
</body>
</html>

3. DisplayImage.ashx (Handler)

<%@ WebHandler Language="C#" Class="ReadImage" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;

public class ReadImage : IHttpHandler
{
    
    public void ProcessRequest (HttpContext context) {
        Int32 theID;
        if (context.Request.QueryString["id"] != null)
            theID = Convert.ToInt32(context.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter specified");

        context.Response.ContentType = "image/jpeg";
        Stream strm = DisplayImage(theID);
        byte[] buffer = new byte[2048];
        int byteSeq = strm.Read(buffer, 0, 2048);

        while (byteSeq > 0)
        {
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 2048);
        }
    }
    public Stream DisplayImage(int theID)
    { 
        string cs = ConfigurationManager.ConnectionStrings["TempConnectionString"].ConnectionString;
           using( SqlConnection connection = new SqlConnection(cs))
           {
            string sql = "SELECT image FROM tblImage WHERE id = @ID";
            using (SqlCommand cmd = new SqlCommand(sql, connection))
            {
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Parameters.AddWithValue("@ID", theID);
                connection.Open();
                object theImg = cmd.ExecuteScalar();
                try
                {
                    return new MemoryStream((byte[])theImg);
                }
                catch
                {
                    return null;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                    connection.Dispose();
                    
                }
            }
        }
        
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

Thanks

Download

[wpdm_file id=5]

isNumber() fuction in c#

You have a string value in your C# program and want to find out if it a numeric value.
Double.TryParse method, which returns true if the input string is a number. Here we see how you can use Double.TryParse to test number strings.

public static bool IsNumeric(string s)
{
    double Result;
    return double.TryParse(s, out Result);  
}        
 
string value = "143";
if (IsNumeric(value)) 
{
  // do something
}
Check string is number,double.tr

Thanks

Edit Gridview Using jQuery Dialog ASP.Net C#

In this article, I’ll explain how to Edit records in ASP.Net GridView control using jQuery Dialog UI. There is many other way to do that but here is the easiest way to do it.

Database:
For this tutorial, I am using Employee database.

CREATE TABLE [dbo].[T_Employees](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FirstName] [nvarchar](20) NULL,
	[LastName] [nvarchar](20) NULL,
	[Department] [nvarchar](40) NULL,
	[Location] [nvarchar](40) NULL
) ON [PRIMARY]
Insert INTO [dbo].[T_Employees] values ('Tanvi','Patel',' Physiotherapy ','Sydney') 
Insert INTO [dbo].[T_Employees] values ('Ashish','Patel','IT','Sydney')    
Insert INTO [dbo].[T_Employees] values ('Vaishu','Patel','Micro','Sydney')  
Insert INTO [dbo].[T_Employees] values ('Bhavik','Patel',' pediatrician ','Sydney')

Connection string:
Below is the connection string to connect to the database.

<connectionStrings>
    <add name="TempConnectionString" connectionString="Data Source=ASHISH;Initial Catalog=Temp;Persist Security Info=True;User ID=sa;Password=********" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Aspx Page:
In this tutorial, there are two aspx pages.

1. Default.aspx — To implement Gridview control
2. EditEmployee.aspx –To Edit Employee

Default.aspx page:
Below HTML Markup of the page you will notice that I have placed a Script Manager and an ASP.Net Update Panel on the page. Inside the Update Panel I have placed an ASP.Net GridView Control along with brnRefreah that will be used to refresh after Edit the records in the GridView Control.

        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
        </asp:ScriptManager>
         <asp:UpdateProgress ID="UpdateProgress1" runat="server">
        <ProgressTemplate>
        <img src="Loading.gif" alt="" />
        </ProgressTemplate>
        </asp:UpdateProgress>

    <asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional" >
   <ContentTemplate>
       
       <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
            DataSourceID="SqlDataSource1">
            <Columns>
            <asp:TemplateField HeaderText="ID">
           <ItemTemplate >
               <a id="popup" href='EditEmployee.aspx?id=<%# Eval("ID") %>' >edit</a>
         </ItemTemplate>
           </asp:TemplateField>
              <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" 
                    ReadOnly="True" SortExpression="ID" />
               
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" 
                    SortExpression="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="LastName" 
                    SortExpression="LastName" />
                <asp:BoundField DataField="Department" HeaderText="Department" 
                    SortExpression="Department" />
                <asp:BoundField DataField="Location" HeaderText="Location" 
                    SortExpression="Location" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:TempConnectionString %>" 
            SelectCommand="SELECT Top 10 * FROM [T_Employees]"></asp:SqlDataSource>

           <asp:Button ID="btnRefresh" Text="refresh" runat="server" 
            onclick="btnRefresh_Click" />
   </ContentTemplate>
</asp:UpdatePanel>

You notice that in gridview I have placed Edit link (line 17 in above code) to pass ID of Employee to EditEmployee page. (For example. ‘editEmployee.aspx?id=1).
Now when user click on Edit link, Dialog box will display and load EditEmployee.aspx page. To create dialog box on click event of Edit link we are going to use jQuery Dialog UI. Here is code

 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/jquery-ui.min.js"></script>
    <link type="text/css" rel="Stylesheet" href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/themes/smoothness/jquery-ui.css">
    <script type="text/javascript">
        $(document).ready(function () {
            $('a#popup').live('click', function (e) {
                
                var page = $(this).attr("href")  //get url of link
              
                var $dialog = $('<div></div>')
                .html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
                .dialog({
                    autoOpen: false,
                    modal: true,
                    height: 450,
                    width: 'auto',
                    title: "Edit Employee",
                    buttons: {
                        "Close": function () { $dialog.dialog('close'); }
                                },
                    close: function (event, ui) {
                        
                       __doPostBack('<%= btnRefresh.ClientID %>', '');  // To refresh gridview when user close dialog
                    }
                });
                $dialog.dialog('open');
                e.preventDefault();
            });
        });
    </script>

In dialog Close event, I use __doPostBack(‘<%= btnRefresh.ClientID %>‘, ”); to refresh Gridview. This code fire btnRefresh_click event thats why we need to place gridview1.databind() in it to refresh gridview.
Codebehide (Default.aspx.cs):

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        GridView1.DataBind();
    }
}

EditEmployee.aspx Page:
In this page, we get Employee ID from Querystring. After getting Employee ID We use sql connection to get FirstName, LastName, Location and Department from Database.

EditEmployee.aspx

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <h3>Edit Employee</h3>
        <asp:Label ID="lblResult" runat="server" ForeColor="Green"></asp:Label>
        <asp:Panel ID="pnlEdit" runat="server">
        
    <p>ID:<asp:TextBox ID="txtID" ReadOnly="true" runat="server"></asp:TextBox></p>
    <p> FirstName: <asp:TextBox ID="txtfName"  runat="server"></asp:TextBox></p>
    <p> LastName:<asp:TextBox ID="txtlNmae"  runat="server"></asp:TextBox></p>
    <p>Department: <asp:TextBox ID="txtDept"  runat="server"></asp:TextBox></p>
    <p>Location:<asp:TextBox ID="txtLocation"  runat="server"></asp:TextBox></p>
<p> <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
    </p>
    </asp:Panel>
    </ContentTemplate>
    </asp:UpdatePanel>
    </form>

Codebehind code: EditEmployee.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class EditPopup : System.Web.UI.Page
{
    string CT = ConfigurationManager.ConnectionStrings["TempConnectionString"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string EID = Request.QueryString["id"];
            
            using (SqlConnection cn = new SqlConnection(CT))
            {
                string query = "Select * from T_Employees where ID='" + EID + "'";
                using (SqlCommand cmd = new SqlCommand(query, cn))
                {
                    cn.Open();
                    SqlDataReader dr = cmd.ExecuteReader();
                    if(dr.Read() )
                    {
                        txtID.Text = EID;
                        txtfName.Text = dr["FirstName"].ToString();
                        txtlNmae.Text = dr["LastName"].ToString();
                        txtDept.Text = dr["Department"].ToString();
                        txtLocation.Text = dr["Location"].ToString();
                    }
                    cn.Close();
                    cn.Dispose();

                }
            }
        }
           
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ///save Employee Recoed code
        ///

        using (SqlConnection cn = new SqlConnection(CT))
        {
            string query = "Update T_Employees  Set FirstName='"+txtfName.Text+"', LastName='"+txtlNmae.Text +"', Department='"+txtDept.Text +"', Location='"+txtLocation.Text +"' where ID='" + txtID.Text  + "'";
            using (SqlCommand cmd = new SqlCommand(query, cn))
            {
                cn.Open();
                cmd.ExecuteNonQuery();
                
                cn.Close();
                cn.Dispose();
                lblResult.Text = "Employee Data Saved!!";
                pnlEdit.Visible = false;
            }
        }
        
    }
}

CSS File to style Gridview:

th {
font: bold 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
color: #4f6b72;
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
border-top: 1px solid #C1DAD7;
letter-spacing: 2px;
text-transform: uppercase;
text-align: left;
padding: 6px 6px 6px 6px;
background: #D5EDEF;
}
 
td {
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
background: #fff;
padding: 6px 6px 6px 6px;
color: #4f6b72;
}
 
td.alt
{
background: #F5FAFA;
color: #797268;
}
 
td.boldtd
{
font: bold 13px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
background: #D5EDEF;
color: #797268;
}

Download

[wpdm_file id=3]

Thanks.

Redirection from iframe in asp.net or javascript

In this tutorial we will learn how to perform redirection from IFrame in asp.net.
For example, I has a webpage that contains the form containing two textboxes and one asp:button. When click on button it redirects the user to another page but problem was that the next page was being opened inside the iframe rather than in parent window because the webpage that containing the form was also in iframe.

Solution 1
Here we using the server side onClick event of asp:button to redirecting user to another page and client side OnClientClick event to open new page in parent window. NewWindow() JavaScript code that we have written in the OnClientClick event of asp:button will take care that user must be redirected to next page within parent window rather than IFrame.

Code: (iFrame)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Ashish Blog</title>
    <script type="text/javascript">
        function NewWindow() {
            document.forms[0].target = "_top";
        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Ashish&amp;amp;#39;s Blog<br />
        UserName:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        Password:<asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="NewWindow();" onclick="Button1_Click"  />
    </div>
    </form>
</body>
</html>
 protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }

Solution 2:

 protected void Button1_Click(object sender, EventArgs e)
    {
       
        ClientScript.RegisterStartupScript(this.GetType(), "redirect", "if(top!=self) {top.location.href = 'Default.aspx';}", true);  
    }

Note:- In case if this code is not working properly in IE9 then you have to give the absolute path of targeting webpage such as

 protected void Button1_Click(object sender, EventArgs e)
    {
       
        ClientScript.RegisterStartupScript(this.GetType(), "redirect", "if(top!=self) {top.location.href = 'http://ashishblog.com/Default.aspx';}", true);  
    }

Currency Exchange Rate in webpage using C# ASP.NET

NOTE: GOOGLE turn off currency API but now you can https://www.google.com/finance/converter?a=1&from=AUD&to=INR

Some time ago I found the following Google API , which provides the currency conversion rates for free. Maybe you’ll find it useful.
In this article, I’ll explain how to get currency rate in ASP.Net using C#.

For example, 1 AUD = ? INR (1 Australian Dollar = ? Indian Rupee )
To get INR from 1 AUD, we need to call google API in following format: ( you can try by paste this url into your web browse)

http://www.google.com/ig/calculator?hl=en&q=1AUD%3D%3FINR
The number 1 before AUD is the amount of dollars or quantity.

Above Url returns a JSON object with the details.:

{lhs: "1 Australian dollar",rhs: "47.8167309 Indian rupees",error: "",icc: true}

As you can see the result is called rhs, but it combines the resulting value with the text “Indian rupees”. Now we will remove the string and store the result as a decimal.

We implement fuction called Convert with three parameter (amount, fromCurrency, toCurrency) which return Exchange rate in decimal.

Code:

public static decimal Convert(decimal amount, string fromCurrency, string toCurrency)
        {
            WebClient web = new WebClient();
 
            string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount);
 
            string response = web.DownloadString(url);
 
            Regex regex = new Regex("rhs: \\\\\\"(\\\\d*.\\\\d*)");
            Match match = regex.Match(response);
 
            decimal rate = System.Convert.ToDecimal(match.Groups[1].Value);
 
            return rate;
        }

Thanks