Wednesday, 8 August 2012

"Data List in asp.net"

datalist.aspx:


<asp:DataList ID="DataList1" runat="server">
    <HeaderTemplate><h1>Data List Control.</h1></HeaderTemplate>
    <SeparatorTemplate><br /><hr /><br /></SeparatorTemplate>
    <ItemTemplate>
   <h2> Page ID : <asp:Label ID="lblpn" runat="server" Text='<%# Eval("AutoID") %>'></asp:Label></h2>
    Page Name: <asp:Label ID="Label1" runat="server" Text='<%# Eval("PageName") %>'></asp:Label> <br / />

    Page Description :<asp:Label ID="Label2" runat="server" Text='<%# Eval("PageDescription") %>'></asp:Label>
    Page Active : <asp:Label ID="Label3" runat="server" Text='<%# Eval("Active") %>'></asp:Label>
   
    </ItemTemplate>

    </asp:DataList>

datalist.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.Data;

public partial class About : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) { MFIll_DetailViews();}

    }

    private void MFIll_DetailViews()
    {
        string strConn = @"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True";
        SqlConnection conn = new SqlConnection(strConn);
        conn.Open();
        SqlCommand cmd = new SqlCommand("select * from mySampleTable", conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DataList1.DataSource = ds.Tables[0];
        DataList1.DataBind();

    }
}



"Detail View in asp.net"


detailview.aspx

<asp:DetailsView ID="DetailsView1" runat="server" Height="50px"
        AllowPaging="True"  DataKeyNames="AutoID"
    Width="125px" EmptyDataText="no data exist in record." AutoGenerateRows="False"
        CellPadding="4" ForeColor="#333333" GridLines="None"
    onitemdeleting="DetailsView1_ItemDeleting"
    oniteminserting="DetailsView1_ItemInserting"
    onitemupdated="DetailsView1_ItemUpdated"
        onmodechanging="DetailsView1_ModeChanging"
        onpageindexchanging="DetailsView1_PageIndexChanging"
        oniteminserted="DetailsView1_ItemInserted"
        onitemupdating="DetailsView1_ItemUpdating">
        <AlternatingRowStyle BackColor="White" />
        <CommandRowStyle BackColor="#FFFFC0" Font-Bold="True" />
        <FieldHeaderStyle BackColor="#FFFF99" Font-Bold="True" />
        <Fields>
            <asp:TemplateField HeaderText="Auto ID" Visible="false">
                <EditItemTemplate>
                    <asp:TextBox ID="editTextBox1" runat="server" Text='<%# Bind("AutoID") %>'></asp:TextBox>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:TextBox ID="insertTextBox1" runat="server" Text='<%# Bind("AutoID") %>'></asp:TextBox>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("AutoID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Page Name">
                <EditItemTemplate>
                    <asp:TextBox ID="editTextBox2" runat="server" Text='<%# Bind("PageName") %>'></asp:TextBox>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:TextBox ID="insertTextBox2" runat="server" Text='<%# Bind("PageName") %>'></asp:TextBox>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("PageName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Page Description">
                <EditItemTemplate>
                    <asp:TextBox ID="editTextBox3" runat="server" Text='<%# Bind("PageDescription") %>'></asp:TextBox>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:TextBox ID="insertTextBox3" runat="server" Text='<%# Bind("PageDescription") %>'></asp:TextBox>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("PageDescription") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Active">
                <EditItemTemplate>
                    <asp:TextBox ID="editTextBox4" runat="server" Text='<%# Bind("Active") %>'></asp:TextBox>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:TextBox ID="insertTextBox4" runat="server" Text='<%# Bind("Active") %>'></asp:TextBox>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("Active") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:CommandField ShowEditButton="True" />
            <asp:CommandField ShowInsertButton="True" />
            <asp:CommandField ShowDeleteButton="True" />
        </Fields>
        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
    </asp:DetailsView>


detailview.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;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) 
        {
            MFIll_DetailView();
        }
    }

    private void MFIll_DetailView() 
    {
        string strConn = @"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True";
     SqlConnection conn = new SqlConnection(strConn);
     conn.Open();
     SqlCommand cmd = new SqlCommand("select * from mySampleTable", conn);
     SqlDataAdapter da = new SqlDataAdapter(cmd);
     DataSet ds = new DataSet();
     da.Fill(ds);
     DetailsView1.DataSource = ds.Tables[0];
     DetailsView1.DataBind();
    
    }

    protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        
        TextBox txtpagename = (TextBox)DetailsView1.FindControl("insertTextBox2");
        TextBox txtdesc = (TextBox)DetailsView1.FindControl("insertTextBox3");
string strConn = @"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True";
     SqlConnection conn = new SqlConnection(strConn);
     conn.Open();

     SqlCommand cmd = new SqlCommand("sp_insert", conn);
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.Parameters.Add("@PageName", txtpagename.Text);
     cmd.Parameters.Add("@PageDescription", txtdesc.Text);
     cmd.ExecuteNonQuery();
     
     MFIll_DetailView();
       

    }
    protected void DetailsView1_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
    {
        DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);       
    }
    protected void DetailsView1_ItemDeleting(object sender, DetailsViewDeleteEventArgs e)
    {

        string strConn = @"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True";
        SqlConnection conn = new SqlConnection(strConn);
        conn.Open();
        DataKey dk = DetailsView1.DataKey;
        int id =int.Parse( dk.Value.ToString());
        string strqry = @"DELETE FROM mySampleTable WHERE AutoID='" + id + "'";
        SqlCommand cmd = new SqlCommand(strqry,conn);
        cmd.ExecuteNonQuery();
        MFIll_DetailView();
        Label5.Text = "Record Deleted....";
       

    }
    protected void DetailsView1_ModeChanging(object sender, DetailsViewModeEventArgs e)
    {
        DetailsView1.ChangeMode(e.NewMode);
        MFIll_DetailView();
        if (e.NewMode == DetailsViewMode.Edit)
        {
            DetailsView1.AllowPaging = false;

        }
        else 
        {
            DetailsView1.AllowPaging = true;
        }
    }
    protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
    {
        DetailsView1.PageIndex = e.NewPageIndex;
        MFIll_DetailView();
    }
    protected void DetailsView1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        DataKey dk = DetailsView1.DataKey;
        int id= int.Parse(dk.Value.ToString());

        TextBox txtpagename = (TextBox)DetailsView1.FindControl("editTextBox2");
        TextBox txtdesc = (TextBox)DetailsView1.FindControl("editTextBox3");
        string strConn = @"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True";
        SqlConnection conn = new SqlConnection(strConn);
        conn.Open();

        SqlCommand cmd = new SqlCommand("sp_update", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@AutoID", id);
        cmd.Parameters.Add("@PageName", txtpagename.Text);
        cmd.Parameters.Add("@PageDescription", txtdesc.Text);
        cmd.ExecuteNonQuery();
        MFIll_DetailView();
       
    }
    protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {
        DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
    }
}

"Bind Data to text boxes from Database"

default.aspx;


<table>
<caption>Add Organizational Details</caption>
<tr><td>Organization Name</td><td>
    <asp:TextBox ID="txtON" runat="server"></asp:TextBox></td></tr>
 
 
    <tr><td>Business Sector</td><td>
    <asp:TextBox ID="txtBS" runat="server"></asp:TextBox></td></tr>
    <tr><td>WEbsite</td><td>
    <asp:TextBox ID="txtWebSite" runat="server"></asp:TextBox></td></tr>
    <tr><td>EmailID1</td><td>
    <asp:TextBox ID="txtEmail1" runat="server"></asp:TextBox></td></tr>
    <tr><td>EmailID2</td><td>
    <asp:TextBox ID="txtEmail2" runat="server"></asp:TextBox></td></tr>
    <tr><td>Address</td><td>
    <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td></tr>
    <tr><td>Organizational Enviroment</td><td>
        <asp:DropDownList ID="ddlOE" runat="server">
            <asp:ListItem Selected="True">Excellent</asp:ListItem>
            <asp:ListItem>Good</asp:ListItem>
            <asp:ListItem>Fair</asp:ListItem>
        </asp:DropDownList>
    </td></tr>
    <tr><td>Term and Condition</td><td>
    <asp:TextBox ID="txtTermCondition" runat="server"></asp:TextBox></td></tr>
    <tr><td>Size of Organization</td><td>
    <asp:TextBox ID="txtSizeOrganization" runat="server"></asp:TextBox></td></tr>
    <tr><td>
        <asp:Button ID="btnInsert" runat="server" Text="Save"
            onclick="btnInsert_Click" /><asp:Button ID="btnUpdateRecord" runat="server"
            Text="Update" onclick="btnUpdateRecord_Click" /></td><td><asp:Button ID="btnUpdate" runat="server"
                Text="Show" onclick="btnUpdate_Click" /></td>
             
                </tr>
    </table>

// ******* Call Method on Click*************

protected void btnShow_Click(object sender, EventArgs e)
    {
        RecordBindData();
    }

//************** Fetch User Profile
    private void RecordBindData()
    {

        DataSet ds = new DataSet();
        rog.rName = Session["UserLogin"].ToString();
       ds= rog.ShowRecruiterProfile();
       if (ds.Tables[0].Rows.Count > 0)
       {
           DataRow dr = ds.Tables[0].Rows[0];
           txtON.Text = dr[2].ToString();
           txtBS.Text = dr[3].ToString();
           txtWebSite.Text = dr[4].ToString();
           txtEmail1.Text = dr[5].ToString();
           txtEmail2.Text = dr[6].ToString();
           txtAddress.Text = dr[7].ToString();

           txtTermCondition.Text = dr[9].ToString();
           txtSizeOrganization.Text = dr[10].ToString();
       }
       else
       {
           ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", @"alert('No Data Found');", true);
       }
 
    }

//************** RecordBindData

 public DataSet fetchUserProfile()
        {
            SqlCommand cmd = new SqlCommand("sp_RODFetch", (SqlConnection)Ncconnection.cconnection.MConnection());
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@RUserName", this._recruiterName);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds;
        }



"Fill Drop down from Database"


//Create Procedure.

create proc [dbo].[sp_BindJobType]
as
select JobId,JobType from tblJobType



//Code to Fill Drop Down

public void MFill_DropJobcategory()
    {
        try
        {
            DataSet ds = new DataSet();
            SqlCommand cmd = new SqlCommand("sp_BindJobType",(SqlConnection)Ncconnection.cconnection.MConnection());
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);

            ddlJobCategoty.DataValueField = "JobId";
            ddlJobCategoty.DataTextField = "JobType";
            ddlJobCategoty.DataSource = ds.Tables[0];
            ddlJobCategoty.DataBind();

            if (ds.Tables[0].Rows.Count > 0)
            {
                ddlJobCategoty.Items.Insert(0, "----Select----");
            }
            else
            {
                ddlJobCategoty.Items.Insert(0, "No Job Type");
            }
        }
        catch (Exception ex) { throw new Exception(ex.Message); }
    }

Tuesday, 7 August 2012

"Report Generate in Excel/Word/PDF in asp.net using c#"


default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" CellPadding="4" AutoGenerateColumns="False"
            EnableModelValidation="True" ForeColor="#333333" GridLines="None"
            Width="1000px" onrowediting="GridView1_RowEditing" >
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="AddressLine1">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("AddressLine1") %>'></asp:TextBox>
                       
                     
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("AddressLine1") %>'></asp:Label>
                       

                    </ItemTemplate>
                    <ItemStyle Width="10%" />
                </asp:TemplateField>
               
                <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="25%" >

<ItemStyle Width="25%"></ItemStyle>

                </asp:BoundField>
                <asp:BoundField DataField="PostalCode" HeaderText="PostalCode"
                    ItemStyle-Width="25%" >

<ItemStyle Width="25%"></ItemStyle>

                </asp:BoundField>
                <asp:BoundField DataField="rowguid" HeaderText="rowguid" ItemStyle-Width="10%" >

<ItemStyle Width="10%"></ItemStyle>

                </asp:BoundField>
                <asp:CommandField ShowEditButton="True" />
            </Columns>
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
        </asp:GridView>

        <br />
        <asp:Button ID="btnReport" runat="server" Text="Export"
            onclick="btnReport_Click" />
       

    </div>
    </form>
</body>
</html>


default.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;
using System.Data.SqlClient;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
       
       SqlConnection conn = new SqlConnection(@"Data Source=SP2010;Initial Catalog=AdventureWorks;Integrated Security=True");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Mfill();
            }
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            Mfill();
        }

        private void Mfill()
        {
            SqlCommand cmd = new SqlCommand("select top 10 AddressLine1,City,PostalCode,rowguid from Person.Address", conn);

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
            Session["Beneficiary_Report"] = ds;
        }

        protected void btnReport_Click(object sender, EventArgs e)
        {
            Export_Data();
        }

        protected void Export_Data()
        {
            try
            {
                if (GridView1.Rows.Count < 1)
                {
                    ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", @"alert('Unable to Find Information to Export');", true);
                    return;
                }
                string ls_item_list = null;
                //first let's clean up the response.object
                Response.Clear();
                Response.Charset = "";
                //set the response mime type for excel
               Response.ContentType = "application/vnd.ms-Excel";
                //Response.ContentType = "application/pdf";
                //Response.ContentType = "application/msword";  // for word
             
                Response.Clear();

                //create a string writer
                System.IO.StringWriter stringWrite = new System.IO.StringWriter();
                //create an htmltextwriter which uses the stringwriter
                System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
                //instantiate a datagrid
                DataGrid dg = new DataGrid();
                DataSet ds1 = null;
                dg.ItemStyle.Font.Size = FontUnit.Medium;
                dg.HeaderStyle.ForeColor = System.Drawing.Color.Black;
                dg.HeaderStyle.Font.Bold = true;
                dg.HeaderStyle.Font.Size = FontUnit.Point(10);
                dg.HeaderStyle.BackColor = System.Drawing.Color.Gray;
               // ds1 = new DataSet();  // for this row print same to same page in excel.

//ds1 = (DataSet)Session["Beneficiary_Report"];   // both are work below use method to return a object 
                ds1 = (DataSet)ReturnSessionVariable("Beneficiary_Report");
                dg.DataSource = ds1.Tables[0];
                dg.DataBind();
                dg.RenderControl(htmlWrite);
                Response.Write(stringWrite.ToString());
                Response.End();
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", @"alert('Unable to Export Informtion Pleae Try again');", true);
            }

        }

        private object ReturnSessionVariable(string key)
        {
            return Session[key];
            //else
            //{
            //    Session["Error_Type"] = EnumErrors.BadRequest;
            //    Response.Redirect("invaliduser.aspx");
            //}
        }

    }
}




"Set width of columns in Gridview and also set width of Grid. "


<asp:GridView ID="GridView1" runat="server" CellPadding="4" AutoGenerateColumns="False"
            EnableModelValidation="True" ForeColor="#333333" GridLines="None" Width="1000px" >
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="AddressLine1">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("AddressLine1") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("AddressLine1") %>'></asp:Label>
                    </ItemTemplate>
                    <ItemStyle Width="10%" />
                </asp:TemplateField>
               
                <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="25%" >
                </asp:BoundField>

                <asp:BoundField DataField="PostalCode" HeaderText="PostalCode"
                    ItemStyle-Width="25%" >
                </asp:BoundField>

                <asp:BoundField DataField="rowguid" HeaderText="rowguid" ItemStyle-Width="10%" >
                </asp:BoundField>

            </Columns>
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
        </asp:GridView>

Monday, 6 August 2012

"File Upload Simple and with restriction"


FileUpload.aspx

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

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" /><br />
        <br />
        <asp:Button ID="btnUploadFile" runat="server" Text="Upload File" OnClick="btnUploadFile_Click" /><br />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
       
        <br />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="This is a required field!"
            ControlToValidate="FileUpload1"></asp:RequiredFieldValidator>
    </div>
    </form>
</body>
</html>

FileUpload.aspx.cs


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

public partial class FileUpload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnUploadFile_Click(object sender, EventArgs e)
    {


//Simple upload without restriction:


        //if (FileUpload1.HasFile)
        //{
        //    try
        //    {
        //        string filePath = Server.MapPath("~/FileUpload/" + FileUpload1.FileName);
        //        FileUpload1.SaveAs(filePath);
        //        //FileUpload1.SaveAs("~/FileUpload/" +
        //        //    FileUpload1.FileName);
        //        Label1.Text = "File Name" +
        //            FileUpload1.PostedFile.FileName + "<br />" +
        //            FileUpload1.PostedFile.ContentLength + "kb <br />" +
        //            "Content Type: " +
        //            FileUpload1.PostedFile.ContentType;
        //    }
        //    catch (Exception ex)
        //    {
        //        Label1.Text = "Error" + ex.Message.ToString();
        //    }

        //}
        //else
        //{
        //    Label1.Text = "You have not Specified a File.";
        //}

//File upload with Restriction:


if (FileUpload1.HasFile)
        {
            int maxFileSize = 1048576;  //1GB
            int fileSize = FileUpload1.PostedFile.ContentLength / 1024;  // For FileSize in MB:  FileUpload1.PostedFile.ContentLength / (1024 * 1024)

            if (fileSize > maxFileSize)
            {
                Label1.Text = "File size exceeded the maximum limit of " + maxFileSize / 1024 + " Kb.";
            }
            else
            {
                string fileExt =
                   System.IO.Path.GetExtension(FileUpload1.FileName);

                if (fileExt == ".mp3")
                {
                    try
                    {
                        string filePath = Server.MapPath("~/FileUpload/" + FileUpload1.FileName);
                        FileUpload1.SaveAs(filePath);
                        Label1.Text = "File name: " +
                            FileUpload1.PostedFile.FileName + "<br>" +
                            FileUpload1.PostedFile.ContentLength + " kb<br>" +
                            "Content type: " +
                            FileUpload1.PostedFile.ContentType;
                    }
                    catch (Exception ex)
                    {
                        Label1.Text = "ERROR: " + ex.Message.ToString();
                    }
                }
                else
                {
                    Label1.Text = "Only .mp3 files allowed!";
                }

            }
        }
        else
        {
            Label1.Text = "You have not specified a file.";
        }
    }
}

//changes in web.config file;


<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>

    <httpRuntime
 executionTimeout="1100"
 maxRequestLength="1048576"
 requestLengthDiskThreshold="80"
 useFullyQualifiedRedirectUrl="false"
 minFreeThreads="8"
 minLocalRequestFreeThreads="4"
 appRequestQueueLimit="5000"
 enableKernelOutputCache="true"
 enableVersionHeader="true"
 requireRootedSaveAsPath="true"
 enable="true"
 shutdownTimeout="90"
 delayNotificationTimeout="5"
 waitChangeNotification="0"
 maxWaitChangeNotification="0"
 enableHeaderChecking="true"
 sendCacheControlHeader="true"
 apartmentThreading="false" />
</system.web> 
</configuration>





Note: Defination for know term:



maxRequestLength - Attribute limits the file upload size for ASP.NET application. This limit can be used to prevent denial of service attacks (DOS) caused by users posting large files to the server. The size specified is in kilobytes. As mentioned earlier, the default is "4096" (4 MB). Max value is "1048576" (1 GB) for .NET Framework 1.0/1.1 and "2097151" (2 GB) for .NET Framework 2.0.

executionTimeout - Attribute indicates the maximum number of seconds that a request is allowed to execute before being automatically shut down by the application. The executionTimeout value should always be longer than the amount of time that the upload process can take.