-->

Friday, August 9, 2013

How to add control to the footer of Gridview in ASP.NET

Top related post


Add FooterTemplate in Gridview
Source code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="footercontrol.aspx.cs" Inherits="footercontrol" %>
<!DOCTYPE html>
<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" AutoGenerateColumns ="false" ShowFooter="True">
            <Columns >
                <asp:TemplateField HeaderText ="header template">
                    <ItemTemplate>
<asp:Label ID="l1" runat ="server" Text ='<% # Eval("Name") %>' />
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:Button ID="Button1" runat="server" Text="Footer template" />
                    </FooterTemplate>
                </asp:TemplateField>

            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
CodeBehind File


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

public partial class footercontrol : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        con.Open();
        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
        cmd.CommandText = "Select * from commentbox";
        cmd.Connection = con;
        System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(cmd);
        System.Data.DataSet ds = new System.Data.DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

Output
How to add control to the footer of Gridview in ASP.NET



Thursday, August 8, 2013

How to use HTTP Handlers in ASP.NET

HTTP Handlers, as the name suggest, handle user requests for  Web application resources. They are the backbone of the request-response model of web applications. For each user request type, there is a specific event handler to handle the request and send back the corresponding response object.
Each user request to the IIS Web Server flows through the HTTP pipeline, which refers to a series of components (HTTP Modules and HTTP Handlers) to process the request. HTTP Modules act as filters to process the request as it passes through the HTTP pipeline. The request, after passing through the HTTP Modules, is assigned to an HTTP Handlers that determines the response of the server to the user request. The response then passes through the HTTP Modules once again and sends back to the server.

You can define HTTP Handlers in the <httpHandlers> section of a configuration file. The <add> element tag is used to add new handlers and the <remove> elements tag is used to remove existing handlers. To create an HTTP Handlers, you need to define a class that implements an IHttpHandler interface. The two methods of the IHttpHandler interface are:

ProcessRequest ( ) : Invoked when a user request is received. It processes the request using the HttpContext object, which is passed as a parameters.
IsReusable ( ) - Determines whether the HTTP Handler object, accessed using the Processrequest ( ) method , can be reused. The HTTP handler object can only be reused if the IsReusable ( ) method returns a true value. The object is discarded when the HTTP Handlers object returns a false value.

Example of HTTP Handlers in ASP.NET

First need to create a class file CustomHandler.cs



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

/// <summary>
/// Summary description for CustomHandler
/// </summary>
namespace CustomHTTP
{
public class CustomHandler : IHttpHandler
{

    public bool IsReusable()
    {
        return true;
    }
    public void ProcessRequest(System.Web.HttpContext context)
    {
        HttpResponse response = context.Response;
        response.Write("<html><body><h2>Example of HTTP Handlers </body></html>");

    }
}
}
Add the code in the section of the web.config file


 <httpHandlers>
      <add verb ="*" path ="CustomHttp.test" type ="CustomHTTP.CustomHandler"/>
 
 
    </httpHandlers>

Wednesday, August 7, 2013

How to use web User Control in ASP.NET

Example of Web User Control

Step-1 : Add Web User Control file in solution explorer name  as " WebUserControl.ascx".
Step-2 :  Drop some controls from tool box to  Designing window of WebUserControl.ascx page .

How to use web User Control in ASP.NET

Step-3 : Add a Web form in Solution explorer name as " usercontroluses.aspx" 
Step-4 : Drop "WebUserControl.ascx " page from solution explorer  to Web form ( usercontroluses.aspx)
Step-5 :  Check your Web Form designing part .
How to use web User Control in ASP.NET


After dropping your web form contain a single Register directive and  one user defined tag.

<%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>

<uc1:WebUserControl ID="WebUserControl1" runat="server" />

Code file of WebUserControl.ascx

<%@ Control Language="C#" ClassName="WebUserControl" %>
<script runat="server">
</script>
<asp:Label ID="Label1" runat="server" Text="UserName"></asp:Label>
&nbsp;:
<asp:TextBox ID="TextBox1" runat="server" Width="189px"></asp:TextBox>
<p>    &nbsp;</p>
<p>    Password :&nbsp;
    <asp:TextBox ID="TextBox2" runat="server" Width="192px"></asp:TextBox>
</p>
<p>
    <asp:Button ID="Button1" runat="server" Text="Submit " />
</p>
Code file of  usercontroluses.aspx


<%@ Page Language="C#" %>
<%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>
<!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>
 
        <uc1:WebUserControl ID="WebUserControl1" runat="server" />
 
    </div>
    </form>
</body>
</html>

Output Caching with the VaryByParam Attribute

Example of output Caching with the VaryByParam Attribute

        <%@ Page Language="C#" %>
<%@ OutputCache Duration ="60" VaryByParam ="Name" %>

<!DOCTYPE html>

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
     
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (IsPostBack )
        {
            Name.Visible = false;
            Label3.Visible = false;
            Button1.Visible = false;
            Label2.Text = "the output of this page was cached for" + Name.Text + "The current time is" + DateTime.Now.ToString();
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
        <asp:Label ID="Label3" runat="server" Text="Please Enter your name:"></asp:Label>
        <asp:TextBox ID="Name" runat="server"></asp:TextBox>
 
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
        <br />
        <asp:Label ID="Label2" runat="server"></asp:Label>
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
 
    </div>
    </form>
</body>
</html>

Output
Output Caching with the VaryByParam Attribute

Output Caching with the VaryByParam Attribute


Validating Input Controls in windows forms C#

Data entered by user, should be valid and properly formatted, Otherwise a lot of resources could be wasted in fixing the problems that could be arise due to incorrect data format. Data should be properly checked according to the input criteria. Windows forms provides some ways to validate input in your application.

Masked TextBox Validation

We often requires some data like contact number in a well-defined format and also correct no of digits. This problem can easily be solved by using MaskedTextBox in windows forms. MaskedTextBox displays some formats to the user. If user types a wrong entry then this textbox automatically reject that input.

Just add a MaskedTextBox control and look out the mask property. There are approx. 9 predefined masks such as Phone number, zip code, Numeric digits etc. as in following screenshot:
Mask options of Masked TextBox in windows forms

There is no mask for mobile no in the above masks, so we have to create a new mask. Use the last mask i.e. custom mask and insert ten zero’s in the mask textbox just below the list of mask because mobile no is of ten digits, and our new mask has been created.

Event-Driven Validation

Each input control has a Validating event that occur whenever the control requires data validation. Validating event enables you to prevent from shifting focus from the control being validated to another control until validation has been completed.

To check whether the textbox is blank or not, we will simply check this by using the following line of codes in validating event of textbox in C# language.
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text == string.Empty)
{
MessageBox.Show("Textbox is empty");
}
}

Just like above code we can validate any other control using some lines of code. There is an argument e of type CancelEventArgs, which can be used to cancel the validating event if required input has been entered by user.
Displaying message when validating the textbox

As in above screenshot if the textbox left empty by the user then a message has been displayed written above. This message can be displayed by any of the message box, status strip etc.

Tuesday, August 6, 2013

How to use caching in ASP.NET

Top related article


Introduction
Caching as the name suggest, is used to store data temporarily either on a Web server or on the client-side. Caching is useful in situation where several programs continually access the same set of data. This data can be easily stored in a cache and used in future. Accessing a database in an ASP.NET page is generally a slow and time-consuming process that involves connecting to the database and retrieving data from it. Caching is the best way to improve the performance of your Web application since it allows you to access data from the cache itself, which is quicker than if you were to retrieve the data from the database on each request. Therefore, caching not only reduces the processing time of a Web application, but also reduces network traffic; thereby improving the performance of your Web application and enhancing user experience.

Example of caching using output caching 


<%@ Page Language="C#" %>
<%@ OutputCache Duration ="10" VaryByParam ="none" %>
<!DOCTYPE html>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        Label2.Text = DateTime.Now.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>  
        <asp:Label ID="Label1" runat="server" Text="The below displayed time was cached for 10 seconds keep refreshing the page to see the changes"></asp:Label>
        </div>
        <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
    </form>
</body>
</html>
Output
How to use caching in ASP.NET

Here in this example time label will changed after 10 second.

VaryByParam Attribute 
The VaryByParam attribute is used to cache different copies of a Web page when it is generated dynamically, based on the parameters received in the form of HTTP POST or HTTP GET.




LinkLabel control in windows forms C#

Label control is used to display the text such as Name, address, title and so on. The text shown through Label control cannot be edited directly by the user. Most often this control is used for providing information of another control in the windows form.

LinkLabel control is, derived from the label control, used to display text as a link. Link may be of a windows form or a website depending on the requirements. It has all the properties of Label control as well as its own properties. The commonly used properties of LinkLabel control are:

  • ActiveLinkColor: used to get or set the color used to display the active link. It is of type Color.
    linkLabel1.ActiveLinkColor = Color.Blue; This code sets the color to blue of an active link in C#.
  • DisabledLinkColor: used to get or set the color used to display the disabled link. It is also of type Color. linkLabel1.DisabledLinkColor = Color.Blue; This code sets the color to blue of an disabled link in C#.
  • LinkColor: used to get or set the color of the text on the LinkLabel control. It is also of type Color. linkLable1.LinkColor = Color.Blue; This code sets the color of the text to blue in C#.
  • LinkVisited: used to get or set a value indicating whether a link should be displayed as though it were visited. It is of type Boolean and default value is false.

LinkClicked event occurs when the link is clicked by the user. This event has an event argument of LinkLabelLinkClickedEventArgs which returns the link that was clicked by the user. The structure of this event is as follows in C#:

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
}

Writing the following code in this event will show a new form

Form2 frm = new Form2();
frm.Show();

To create a link to a website, we should use following code:

System.Diagnostics.Process.Start(“http://dotprogramming.blogspot.in”);

In the above code the method Start() starts the default browser with the given URL.
© Copyright 2013 Computer Programming | All Right Reserved