Friday, November 25, 2011

Upload, Save and Retrieve Image

  This article shows you how to upload,save and retrieve image in asp.net using c#. Basically we can do this in two way.The first one is we can save the image in any specific folder and in database save the path and to retrieve it just bind the path to image url. And in another way we can save the image in binary format in database.Now at first place the image control, file upload control and button in your aspx page.

<asp:Image ID="imgMem" runat="server" Height="116px" BorderColor="Black"  BorderStyle="Double" ImageUrl="~/Images/userimage.jpg" Width="150px" EnableTheming="False" />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" onclick="btnUpload_Click"  Text="Upload" />

In button click event write down the code given below.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            path = Server.MapPath("~/Library/Images/");
            FileUpload1.SaveAs(path+FileUpload1.FileName);
            picnm = FileUpload1.FileName;
           /* If Path exists then set path to ImageUrl & hold the value on ViewState */
            ViewState["picnm"] = picnm;
            imgMem.ImageUrl = "~/Library/Images/" + FileUpload1.FileName;
        }
    }

In database define the field as varchar. And  save it in your own way.
  cmd.Parameters.AddWithValue("@img",ViewState["picnm"].ToString());

To retrieve the image fetch the field value and bind it to image url.
 imgMem.ImageUrl = "~/Library/Images/" + dr["MemPic"].ToString();

Now to save image in binary format write given code in button's click event
  if (FileUpload1.HasFile)
            {
                 // Create a byte[] from the input file
                len = FileUpload1.PostedFile.ContentLength; // Here len is integer
                if(len > 409600)
                {
                    CloseWindow = "alert('Picture size is too large.Maximum file size is 400KB.');";
                    ScriptManager.RegisterStartupScript(this.UpdatePanel_St, this.UpdatePanel_St.GetType(),       "CloseWindow", CloseWindow, true);
                    return;
                }
                pic = new byte[len]; //pic is an array of byte type
                FileUpload1.PostedFile.InputStream.Read(pic, 0, len);
                ViewState["pic"] = pic;
                Session["img"] = pic;
                imgMem.ImageUrl = "GetImgBefSave.aspx";

            
            }

To retrieve the image before save create a blank web form and write down the below code in its cs file.

public partial class Library_GetImgBefSave : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindImg();
    }
    public void BindImg()
    {
        byte[] pic = (byte[])Session["img"];
        Response.BinaryWrite(pic);
    }
}

Now to save the image write down the code given below.
  byte[] img = (byte[])ViewState["pic"];
  query = "INSERT INTO [dbo].[test] ([pic]) VALUES (@img)";
  SqlCommand cmd = new SqlCommand(query,con);
  cmd.CommandType = CommandType.Text;
  cmd.Parameters.AddWithValue("@img", img);
  if (con.State == ConnectionState.Closed)
        con.Open();
  cmd.ExecuteNonQuery();
  con.Close();

To retrieve the image create a new blank web form.In the code behind write down the below code.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Library_getimg : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EduComERPConnectionString"].ConnectionString);
    string query = null;
    string id = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        id = Request.QueryString["ID"];
        if (!IsPostBack)
        {
            GetImg();
        }
    }
    public void GetImg()
    {
        query = "SELECT [MemPic] FROM [dbo].[tbl_LibMemInfo] where [Lib_Id]=" + id + "";
        SqlCommand cmd = new SqlCommand(query,con);
        cmd.CommandType = CommandType.Text;
        if (con.State == ConnectionState.Closed)
            con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            if (dr["MemPic"].ToString() != "")
            {
                byte[] img = (byte[])dr["MemPic"];
                Response.BinaryWrite(img);
            }
        }
        dr.Close();
        con.Close();
    }
}


Now bind the address of this web form to image url.

 imgMem.ImageUrl = "getimg.aspx?ID=" + dr["Lib_Id"].ToString();
    


Check or uncheck items in a checkbox list, based on information

This example shows you the way to get the value of checked items and then again check the checkbox a/c to the values.
 foreach (ListItem val in ChklPeriod.Items)
 {
      if (val.Selected)
            ViewState["data"] += val.Text + ",";  //store the selected values in viewstate separated by a comma
 }

Now to check the checkboxlist a/c to the stored values use the method given below.
if (ViewState["data"] != null)
{
      foreach (string s in ViewState["data"].ToString().Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
      {
             foreach (ListItem l in ChklPeriod.Items)
                        if (l.Text == s)
                            l.Selected = true;
      }
}

Wednesday, November 23, 2011

Concatenate two fields in sql server

Sometime we need to concatenate two or more fields n show them in formatted manner.If all the fields are varchar then its not a big deal just use the technique given below.

SELECT [PartyNm]+' ( '+ [TempAdd] +', '+ [ContactNo]+' )' as name  FROM [dbo].[tbl_AccountMaster]

But you have to face problem if the fields are int type or containing numbers only.In this scenario it add values instead of concatenation.
 SELECT  [Unit_Id]+[BD_Id] as ID FROM [dbo].[MST_Unit]

So to overcome this issue you have to convert the field into varchar than try to concatenate,this will give you the desired result.

SELECT '('+CONVERT(varchar,[Unit_Id])+'-'+convert(varchar,[BD_Id])+')' as ID FROM [dbo].[MST_Unit]

If you will attempt to concatenate columns without conversion like this one,
SELECT '('+[Unit_Id]+'-'+convert(varchar,[BD_Id])+')' as ID FROM [dbo].[MST_Unit]
Then got the following error

Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value ' )' to data type int.

Thursday, November 17, 2011

String or binary data would be truncated. The statement has been terminated.

Very often you will get errors like "String or binary data would be truncated. The statement has been terminated". We just wandered why we encountered by this error while everything seems right.But this error simply says you are updating the column with larger size than what it can accommodate.So don't worry just check your field length or your entry for spaces.



Tuesday, November 15, 2011

Add Month To any Given Date

Given example shows you how to add months to a given Date.

using System.Globalization;

protected void DropEMISchedule_SelectedIndexChanged(object sender, EventArgs e)

{

DateTime dt;

int calcy = Convert.ToInt32(DropEMISchedule.SelectedValue) * Convert.ToInt32(txttenure.Text);

if (DateTime.TryParseExact(txtEMIStartDate.Text, "dd/MM/yyyy",new CultureInfo("en-US"),  System.Globalization.DateTimeStyles.None, out dt))

{

TextBoxend.Text = "";

DateTime dtshow = dt.Date.AddMonths(calcy);

TextBoxend.Text = (dtshow).ToString("dd/MM/yyyy");

}

}

Convert Number to Text

Function below can be used in converting any number into text.
 
public string NumberToText(int number)
    {
        if (number == 0) return "Zero";
        if (number == -2147483648) return "Minus Two Hundred and Fourteen Crore Seventy Four Lakh     Eighty Three Thousand Six Hundred and Forty Eight";
        int[] num = new int[4];
        int first = 0;
        int u, h, t;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (number < 0)
        {
            sb.Append("Minus ");
            number = -number;
        }
        string[] words0 = { "", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine " };
        string[] words1 = { "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };
        string[] words2 = { "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety " };
        string[] words3 = { "Thousand ", "Lakh ", "Crore " };
        num[0] = number % 1000; // units
        num[1] = number / 1000;
        num[2] = number / 100000;
        num[1] = num[1] - 100 * num[2]; // thousands
        num[3] = number / 10000000; // crores
        num[2] = num[2] - 100 * num[3]; // lakhs
        for (int i = 3; i > 0; i--)
        {
            if (num[i] != 0)
            {
                first = i;
                break;
            }
        }
        for (int i = first; i >= 0; i--)
        {
            if (num[i] == 0) continue;
            u = num[i] % 10; // ones
            t = num[i] / 10;
            h = num[i] / 100; // hundreds
            t = t - 10 * h; // tens
            if (h > 0) sb.Append(words0[h] + "Hundred ");
            if (u > 0 || t > 0)
            {
                //if (h > 0 || i == 0) sb.Append("and ");
                if (t == 0)
                    sb.Append(words0[u]);
                else if (t == 1)
                    sb.Append(words1[u]);
                else
                    sb.Append(words2[t - 2] + words0[u]);
            }
            if (i != 0) sb.Append(words3[i - 1]);
        }
        //  sb.Append(" Rupees Only");
        return sb.ToString().TrimEnd();
    }

And if you want to convert Rupees value in word then one can use this idea.Here lblBUnit contains the bigger unit of any currency and lblSUnit holds the value of smaller unit of any currency.

             int i = 0;
            String[] val = lbltotal_amount.Text.Split('.');
            foreach (string s in val)
                i++;
            lbltotal_amountinword.Text = NumberToText(Convert.ToInt32(val[0]));
            if (i == 1)
                lbltotal_amountinword.Text = lbltotal_amountinword.Text + " " + lblBUnit.Text + " Only";
            else
                lbltotal_amountinword.Text = lbltotal_amountinword.Text + " " + lblBUnit.Text + " and " +    NumberToText(Convert.ToInt32(val[1])) + " " + lblSUnit.Text + " Only";

Show Total in GridView Footer

 Given Example shows you how to calculate total of particular cells value and show at the footer of Gridview.
At first define footer template in template field for which you want to calculate total.


<asp:TemplateField HeaderText="Total Pcs">
 <ItemTemplate>
          <asp:Label ID="lbltotpcs" runat="server"  Text='<%# Bind("totpcs") %>'></asp:Label>
 </ItemTemplate>
 <FooterTemplate>
        Total : <asp:Label ID="lbltotqty" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
</asp:TemplateField>


Populate the RowDataBound event of Gridview where you have to do the main calculation.

int totqty=0;
protected void gvCrate_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label totpcs = (Label)e.Row.FindControl("lbltotpcs");
            totqty = totqty + (Convert.ToInt32(totpcs.Text));
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            ((Label)e.Row.FindControl("lbltotqty")).Text = totqty.ToString();
            TxtTotalpcs.Value = totqty.ToString();
        }
    }

Enable  "ShowFooter" as True in Gridview's property.