Friday, December 23, 2011

Serial No in Gridview

To show serial no in GridView just embed this code within Template Field :


<asp:TemplateField>
  <ItemTemplate>
   <table class="style2">
       <tr>
      <td>
        <%#Container.DataItemIndex+1 %>
     </td>
    </tr>
   </table>
 </ItemTemplate>
</asp:TemplateField>




Friday, December 16, 2011

Confirm Message Box using C# in Web Application

To use windows confirm message box in web form at first add window namespace in your cs file.
using System.Windows;
Then add code given below to your desired place.
 
System.Windows.Forms.DialogResult dia = System.Windows.Forms.DialogResult.Yes;

if (gvOrder.Rows.Count > 0)
{
    dia = System.Windows.Forms.MessageBox.Show("Previous Order Is Not Placed Yet.Do U want to      Discard Order? ", "DELETE?", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, System.Windows.Forms.MessageBoxDefaultButton.Button1, System.Windows.Forms.MessageBoxOptions.ServiceNotification);
    if (dia == System.Windows.Forms.DialogResult.Yes)
     {
    //Place Your Code Here

     }

}
else
{
    //Place Your Code Here
}

Put New Line In C#

In C we have a habit  of using "\n" for new line and "\r" for  carriage return.Some operating systems use the value 0x0a ('\n') to mark the end of a line. Some use the value 0x0d ('\r') to mark the end of a line. Some use the sequence 0x0d,0x0a ("\r\n"). "\r\n" is a carriage return followed by a newline. Since the days of teletype machines is mostly gone, \r\n is usually converted to just \n and handled that way. But the notable thing is that Windows  uses NewLine as "\r\n"  whereas  "\n" in Unix.
 In C# you can use "Environment.NewLine" also. Here the code explaining example -:


 Label1.Text = "First Line" + Environment.NewLine + "Next Line";
 TextBox1.Text = "First Line" + Environment.NewLine + "Next Line";
 TextBox2.Text = "First Line\nNext Line";
You have to  change textmode property of textbox from singleline to multiline otherwise you wont be able to see the effect like you cant see this effect in Label.

Thursday, December 15, 2011

Error converting data type varchar to bigint

Several times you need to convert a varchar field containing alphanumeric value.Like this one :
select [Order_Code]  From [dbo].[Trans_Order]
Using Substring method we can get numeric value.
select SUBSTRING([Order_Code],3,LEN([Order_Code]))  From [dbo].[Trans_Order]
But by using convert or cast method you encountered with a message "Error converting data type varchar to bigint".
select convert(bigint,SUBSTRING([Order_Code],3,LEN([Order_Code])))  From [dbo].[Trans_Order]
So,the actual way to convert any varchar containing only numeric value,is to use ISNUMERIC() method .
In where clause of select statement just check whether string returned by substring method is numeric or not.If its number only then convert or cast method will do their work comfortably.

Now you can use MAX method to get the max value also.








Wednesday, December 14, 2011

Get returned value from Stored Procedure

This example shows you how to get returned value from Stored Procedure.First of all create a stored procedure which returns a value.In this example of stored procedure it receives a parameter named "uname".
Then its getting the Id of user from function fn_getUserBD_ID and returns that value.

Create PROCEDURE sp_GetBDID
@uname varchar(25)=null
AS
 declare @dbBD_id bigint
BEGIN
    SET NOCOUNT ON;
    Select @dbBD_id=dbo.fn_getUserBD_ID(@uname)
    return @dbBD_id
END

Now to get the value write this code in code behind
    public void GetBDID()
    {
        string st = Session["BDGen"].ToString();
        SqlCommand cmd = new SqlCommand("sp_GetBDID", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@uname", st);

        // Return value as parameter
        SqlParameter returnValue = new SqlParameter("returnVal", SqlDbType.Int);
        returnValue.Direction = ParameterDirection.ReturnValue;
        cmd.Parameters.Add(returnValue);

        if (con.State == ConnectionState.Closed)
            con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        lblUId.Text = returnValue.Value.ToString();
    }

Tuesday, December 6, 2011

Case Statement in Sql Server

We can use CASE expression in the SELECT list, WHERE clauses, HAVING clauses, IN lists, DELETE and UPDATE statements, and even inside of built-in functions.

A Simple Example :
select case due_amt when 0 then 'Paid' else due_amt end as FeeStatus from dbo.tbl_feeinfo




error code 0x8007045D

Meaning of Error 0x8007045d is "ERROR_IO_DEVICE" i.e. "The request could not be performed because of an I/O device error. There are various cause for this error like :
  1.  May be the brand of the disc is incompatible with the burner.
  2. May be the disc is defective.Use another one .
  3. May be the burner have malfunctioned.
In summary, "error code 0x8007045D" simply means the media is bad.

Friday, December 2, 2011

Get Connection String Information without any help of Database


Today I m going to show you how to get the connection string value without any help of sql server and visual studio.
Step 1-: Create a blank text document, save it as all files and give file name as “a.udl”.
 Step 2-: Now double click it.It will open as given screen shot.

Step 3-: Select database provider in provider tab and click next.
Step 4-: Then in Connection tab provide all necessary details and finally click ok.
 Step 5-: Now open your udl file in text format i.e. notepad where you wil find your Connection String.



Thursday, December 1, 2011

Nested Grid Through ADO.NET

Today I am going to show you how to implement the nested grid through ADO.NET. We can get various example of nested grid which are implemented through linq or sqldatasource or objectdatasource.
ScreenShots of Output are given below--:



In aspx put the grid in the given way-:
        <asp:GridView ID="gvParent" runat="server" AutoGenerateColumns="False"
            BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px"
            CellPadding="3" CellSpacing="1" GridLines="None"
            onrowcommand="gvParent_RowCommand">
            <Columns>
                <asp:BoundField DataField="Grp_Id" HeaderText="ID" SortExpression="Grp_Id" />
                <asp:BoundField DataField="GrpNm" HeaderText="Name" SortExpression="GrpNm" />
                <asp:TemplateField HeaderText="Group">
                    <ItemTemplate>
                        <asp:Button ID="btnShowChild" runat="server"
                            CommandArgument='<%# Bind("Grp_Id") %>' CommandName="ShowChild" Text="+" />
                             <asp:Button ID="btnHideChild" runat="server"
                            CommandArgument='<%# Bind("Grp_Id") %>' CommandName="HideChild" Text="-" Visible="false" />
                        <asp:GridView ID="gvChild" runat="server" AutoGenerateColumns="False">
                            <Columns>
                                <asp:BoundField DataField="Acct_Id" HeaderText="AcctId"
                                    SortExpression="Acct_Id" />
                                <asp:BoundField DataField="PartyNm" HeaderText="Party Name"
                                    SortExpression="PartyNm" />
                                <asp:BoundField DataField="TempAdd" HeaderText="Address"
                                    SortExpression="TempAdd" />
                            </Columns>
                        </asp:GridView>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
            <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#594B9C" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#33276A" />
        </asp:GridView>



Code Behind File will be like this--:

using System;
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 _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbMandiConnectionString"].ConnectionString);
    string query = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindParentGrid();
        }
    }
    public void BindParentGrid()
    {
        query = "SELECT [Grp_Id] ,[GrpNm]  FROM [dbo].[tbl_Group]";
        SqlDataAdapter sdap = new SqlDataAdapter(query, con);
        DataSet ds = new DataSet();
        sdap.Fill(ds);

        gvParent.DataSource = ds;
        gvParent.DataBind();
        ds.Clear();
    }
    protected void gvParent_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName== "ShowChild")
        {
            query = "SELECT *  FROM [dbo].[tbl_AccountMaster] where [Grp_Id]="+e.CommandArgument.ToString()+"";
            SqlDataAdapter sdap = new SqlDataAdapter(query, con);
            DataSet ds = new DataSet();
            sdap.Fill(ds);
            for (int i = 0; i < gvParent.Rows.Count; i++)
            {
                if (e.CommandArgument.ToString() == (gvParent.Rows[i].Cells[0].Text))
                {
                    ((GridView)gvParent.Rows[i].FindControl("gvChild")).DataSource = ds;
                    ((GridView)gvParent.Rows[i].FindControl("gvChild")).DataBind();
                    ((Button)gvParent.Rows[i].FindControl("btnShowChild")).Visible = false;
                    ((Button)gvParent.Rows[i].FindControl("btnHideChild")).Visible = true;
                }
            }
        }
        if (e.CommandName == "HideChild")
        {
          
            for (int i = 0; i < gvParent.Rows.Count; i++)
            {
                if (e.CommandArgument.ToString() == (gvParent.Rows[i].Cells[0].Text))
                {
                    ((GridView)gvParent.Rows[i].FindControl("gvChild")).DataSource = null;
                    ((GridView)gvParent.Rows[i].FindControl("gvChild")).DataBind();
                    ((Button)gvParent.Rows[i].FindControl("btnShowChild")).Visible = true;
                    ((Button)gvParent.Rows[i].FindControl("btnHideChild")).Visible = false;
                }
            }
        }
    }
}

Put new line character in select statement

Several times we need to show the values in new line which is fetched thorugh select statement and put them in a label or textbox. Then there is a function CHAR() in sql server through which we can get our desired result.

Control character Value
Tab char(9)
Line feed char(10)
Carriage return char(13)
Example-:
select profile + CHAR(13)+CHAR(10) + address +CHAR(13)+CHAR(10)+phone, export_ref from tbl_profile

Output will be like that-:



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";