-->

Friday, April 18, 2014

Add weeks in existing date ASP.NET example

Introduction

Using Add Days method  you can add weeks in integer (converts weeks in days), Object will be updated with new date. This method is used where you want to calculate date after some days. Like Library management project. Lets take an simple example

<form id="form1" runat="server">
    <asp:Button ID="Button1"
    runat="server"
    BackColor="#99CCFF"
    onclick="Button1_Click"
    Text="Click" />
    <div>  
    <asp:Label ID="Label1"
    runat="server"
    BackColor="Yellow"></asp:Label>  
    </div>
    </form>
Code Behind 
protected void Button1_Click(object sender, EventArgs e)
        {        
            DateTime today = DateTime.Today;        
            DateTime after2week = today.AddDays(14);            
            DateTime after4weeks = today.AddDays(28);
            Label1.Text = "today= " + today.ToLongDateString();
            Label1.Text += "<br /><br />after added two weeks with today=";
            Label1.Text += after2week.ToLongDateString();
            Label1.Text += "<br /><br />after added 4 weeks with today=";
            Label1.Text += after4weeks.ToLongDateString();

        }
Code generate the following code

Add weeks in existing date ASP.NET example

Add days in existing date ASP.NET example

Introduction

Using AddDays method  you can add Days in integer, Object will be updated with new date. This method is used where you want to calculate date after some days. Like Library management project. Lets take an simple example
<form id="form1" runat="server">
    <div>  
        <asp:Button ID="Button1"
        runat="server"
        BackColor="#66CCFF"
        onclick="Button1_Click" Text="Click" />  
    </div>
        <asp:Label ID="Label1"
        runat="server"
        BackColor="Yellow"></asp:Label>
    </form>
Code Behind-
protected void Button1_Click(object sender, EventArgs e)
        {          
            DateTime today = DateTime.Today;
            DateTime after2Days = today.AddDays(2);
            Label1.Text = "today= " + today.ToLongDateString();
            Label1.Text += "<br /><br />after added 2 days with today= ";
            Label1.Text += after2Days.ToLongDateString();

        }  
OutPut-


Add days in existing date ASP.NET example

Add months in existing date example in ASP.NET

Introduction

Using AddMonths method  you can add months in integer, Object will be updated with new date. This method is used where you want to calculate date after some months. Like Library management project. Lets take an simple example


<form id="form1" runat="server">
    <div>  
        <asp:Button ID="Button1"
        runat="server"
        onclick="Button1_Click"
        Text="Click"
        BackColor="#99CCFF" />  
    </div>
        <asp:Label ID="Label1"
        runat="server"
        BackColor="Yellow"></asp:Label>
    </form>
CodeBhindeCode-
 protected void Button1_Click(object sender, EventArgs e)  
        {        
            DateTime now = DateTime.Now;        
            DateTime after3Months = now.AddMonths(3);
            Label1.Text = "now = " + now.ToLongDateString();
            Label1.Text += "<br /><br />after added 3 months to now= ";
            Label1.Text += after3Months.ToLongDateString();

        }
OutPut
 Add months in existing date example in ASP.NET

Example of Array.Copy ( ) method in ASP.NET

Introduction

If you want to run array until at specified position, you can simply use copy ( ) method. In this method define some parameters. Like array name, index where you want to start from,ending index etc.
<form id="form1" runat="server">

    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click"
        BackColor="#99CCFF" />
    <div>  
        <asp:Label ID="Label1" runat="server" BackColor="Yellow"></asp:Label>  
    </div>
    </form>


Code behind code
 protected void Button1_Click(object sender, EventArgs e)
    {
        {
            string[] Fruits = new string[]
        {
            "Apple",
            "Banana",
            "Mango",
            "Orange",  
        };
            Label1.Text = "Fruits array: <br />";
            foreach (string s in Fruits)
            {
                Label1.Text += s + "<br />";
            }        
            int length = 3;          
            int index = 1;
            string[] copiedarray = new string[length];
            Array.Copy(Fruits, index, copiedarray, 0, length);
            Label1.Text += "<br /> New array from Fruits array [index no 1 to 3]:<br />";
            foreach (string s in copiedarray)
            {
                Label1.Text += s + "<br />";
            }
        }
OutPut-

Wednesday, April 16, 2014

Computer Programming : How to change data without postback in ASP.NET

News From Computer Programming: In ASP.NET you can't change the data without post-back, if you want to change data without post back, you can use AJAX technology. In previous article we have already learned more about AJAX like, How to install AJAX control Toolkit to the Toolbox or many more. Today we will learn How to update your GridView data in every seconds, for this you can use Timer control.
The Timer control is used for updating contents of the UpdatePanel control at predefined intervals. Single Timer control can refresh  more than one UpdatePanel control simultaneously. The Timer control  has an Interval property for defining the timer limit after which the content gets refreshed. When this interval limit gets over, the Tick event is raised . You can handle this event for updating the content values defined in the UpdatePanel control. The Timer control can be used either inside the UpdatePanel control or outside the UpdatePanel control. Now, let's try to understand the UpdatePanel control in both ways.

Timer control Inside the UpdatePanel Control

To use the Timer control inside the UpdatePanel control, drag and drop from the Toolbox as a sub-element of the <ContentTemplate>tag and follow the following steps:
1. Set the interval property of the Timer control as 1000 that equal to 1 second as it takes value in milliseconds.
2.Now, double-click the Timer control in design mode. It will generate event handler function in the code-behind file to handle the Tick event.

Timer Control Outside the UpdatePanel Control

You can use the Timer control outside the UpdatePanel control. This approach is appropriate when there are more than one UpatePanel control in the same Web page and you need to use same Timer control for all or some of them. To do so, you need to perform some changes in your application. However, these changes will not affect the output of your application. First, drag-and-drop the Timer control from the toolbox. Drop it after the ScriptManager control and before the UpdatePanel control; and configure its properties in the following way:
The ScriptManager Tag:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>


The Timer control outside the UpdatePanel control and after the ScriptManager Tag:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

        <asp:Timer ID="Timer1" runat="server" Interval ="1000" OnTick ="Timer1_Tick"></asp:Timer>
Configure the UpdatePanel Control's <Triggers> Element for referencing the timer control in the following way:

   <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID ="Timer1" EventName ="Tick" />
            </Triggers>
        </asp:UpdatePanel>
Lets take a simple example to update GridView Data:
Step-1 : Add ScriptManager and UpdatePanel control after Form tag
Step-2 : Add Content template inside UpdatePanel Control.  
Step-3 : Add Timer control inside ContentTemplate with Tick event and Interval property.
Step-4 : Also add GridView control inside the Content Template.
Step-5 : Bind GridView Control in Tick event.
 Complete Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">



        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
       
       
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
           <ContentTemplate>



               <asp:Timer ID="Timer1" runat="server" Interval ="1000" OnTick ="Timer1_Tick"></asp:Timer>



               <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1">
                   <Columns>
                       <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
                       <asp:BoundField DataField="Name " HeaderText="Name " SortExpression="Name " />
                       <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                   </Columns>
               </asp:GridView>

               <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Table]"></asp:SqlDataSource>
           </ContentTemplate>
        </asp:UpdatePanel>
    <div>
   
    </div>
    </form>
</body>
</html>
Code File
 protected void Timer1_Tick(object sender, EventArgs e)
    {
        GridView1.DataBind();
    } 
Output
Computer Programming : How to update data, without postback
in above snap, if you change data in database table from server explorer, output affected on browser. 

How to make Custom error page in asp.net

If the error isn't properly handled anywhere ,it generates an ugly error message that your visitor will see -- you don't want this to happen

So add a custom error page to your site that your visitor will see in case an unhandled error happens. That page will politely ask the visitor to come back later.

Report the error once again , so the Administrator knows that this serious error gets to the visitor and needs to be taken care of as soon as possible.

Steps to follow for add custom error page:

  1. In Solution Explorer , Double-click web.config and add the following element as a child of the                     
<system.web>
      <customErrors mode ="RemoteOnly"  defaultRedirect ="errorpage.aspx" />

Note : If you want to handle errors using status code then specifies status code in <error> tag. Like

<customErrors mode ="On" defaultRedirect ="http://www.google.com">
      <error statusCode ="404" redirect ="errorpage.aspx"/>     
      
    </customErrors>


2. Add a new web form to your application's root , named errorpage.aspx . This form should not use a Master page , to make sure nothing gets in the way of displaying out simple error . The page also doesn't need a code-behind file

Note: After this change , remote clients will be forwarded to errorpage.aspx when unhandled exceptions are thrown ; however on the local machine you will still receive detailed error information . if you want to see the same error message as your visitors , set mode to On instead of RemoteOnly

3. Write some message into your errorpage.aspx like


<%@ Page Language="C#" %>

<!DOCTYPE html>


<script runat="server">


</script>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   Your requested generated an error message 
        we apolgize for the inconvenience.

    </div>

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

4. Test your application by generating error 

How to make Custom webserver control in asp.net

How to make custom server control in asp.net
First draw picture of the custom server control in mind, after make custom control. Suppose we have a picture and we want to make server control of that picture.
Follow some steps for creating custom server control in asp.net

Step-1 : Open visual studio
Step-2:  Goto file-->new-->project-->select web in left pane-->select asp.net server control in middle pane
Step-3:  Write name of your project as 'customserver_control' and click on 'ok' button
Step-4:  After click on ok button you can see 'ServerControl1.cs' file is appear
Step-5:  Change  c# file name as 'customtextbutton' control
Step-6:  Remove this code, which is mentioned below from your c# file

[Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null)? "[" + this.ID + "]" : s);
            }

            set
            {
                ViewState["Text"] = value;
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write(Text);
        }

Step-7: Replace your code with mentioned below code.
[ToolboxData("<{0}:customtextbutton runat=server></{0}:customtextbutton>")]
Note: class name or tag name are same

Step-8: Design CreateChildControls() override method in the class with some statements, which is mentioned below.
Step-9: Now,Your code look like

Label l1:
        TextBox User_txt;
Label l1;

protected override void CreateChildControls()
        {
                l1=new Label();
                l1.ID = "label1";
                l1.Text = "User_Name";
                User_txt = new TextBox();
                User_txt.ID = "usrtxt";
                User_txt.Text = string.Empty;
this.controls.add(l1);
this.controls.add(User_txt);


        }

Step-11: Take override  Render(HtmlTextWriter writer) method  for rendering the object onto the browser
Step-12: write this code inside this method
protected override void Render(HtmlTextWriter writer)
        {
            l1.RenderControl(writer);
            User_txt.RenderControl(writer);


        }

Step-13: Build this project

Now how to use .dll or .exe file in your web application

Step-1: click file-->new-->project-->selct web in left pane-->asp.net web form
Step-2: Right click on tool box and choose new item
Step-3: Browser your project .dll file and add your control onto your toolbox.
© Copyright 2013 Computer Programming | All Right Reserved