DOT NET – How to make a button as default button and set Focus on a particular text box

In the initial days when i was new to development side and in some site i used to login straight away when i enter username and password and hit Enter key on my keyboard.

I used to think how is this happening but never had any answer but now i am going to show how thats possible.

In this post I will be talking about how  to make any button Default button and set Focus on a particular text box in any page thats displayed.

Ex: Make a test site and go to default.aspx

Step 1:

in <body> tag write the following code

<body>

<form id=”frmExample” runat=”server” defaultbutton=”btnLogin” defaultfocus=”txtUserName”>

<table><tr><td width=”50%”>

Welcome to the Example Web site from dilip

</td>

<td width=”50%”>

<table>

<tr><td><asp:TextBox ID=”txtUserName” runat=”server” Text=”UserName” /></td><td><asp:TextBox ID=”txtPassword” runat=”server” Text=”Password”/></td></tr>

<tr><td><asp:Button ID=”btnLogin” runat=”server” Text=”Login” onclick=”btnLogin_Click”/></td><td><asp:Button ID=”btnSignIn” runat=”server” Text=”Signup”/></td></tr>

</table>

</td>

</tr>

</table>

</form>

</body>

Note: Here the beauty is that i have login and singnup button and i made defaultbutton as login button, and defaultfocus on username text box so whenever this page is viewed from any web browser focus will be on username text box and default button will be login button so when u hit enter it will invoke login button so simple.

 Step 2: see  carefully i have a function onclick=”btnLogin_Click” now press F7 key and go to .cs side of the same page or right click on the mouse and select view code .

and write the following code in .cs side

protected void btnLogin_Click(object sender, EventArgs e)

{

Response.Write(“Default Button was clicked and u are now logged In”);

Response.End();

}

Note: Here another concept when ever you enter key this method will be invoked and at the same time there wont be any other you can see that means response is closed just to make you feel that you really logged in but actually u are in same page.

the output is some this like this :

First Time when visited:

you can see username text box is in focus.

Then when enter key is pressed:

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

Advertisements

What is HTTP

HTTP Stands for Hypertext Transfer Protocol.

It is basically used to communicate web pages to web browsers,(HTTP) is used by web servers.When your browser connects to a web server, requests a web page from the server, and downloads the page,HTTP is used. It is a common standard that enables any browser to connect to any server, anywhere in the world.

HTTP was originally designed by Tim Berners-Lee to support the special demands of web communications and with an emphasis on efficiency, and a target page load time of under a tenth of a second. Modern Internet networks can support this type of response provided the page isn’t too large and the server is too far away.

To download different parts of a web page, downloading the text, graphics, and other objects on the page in different orders,your browser can open more than one HTTP connection at once. That is why you may see the status messages in the bottom of your browser window switch between a message like “downloading 38% of 47K” to “downloading 62% of 15K” on the same page — there are different HTTP connections.

To specify the download priorities,some browsers enable you so that, for example, graphics are not loaded, text is loaded before graphics, everything is loaded at once, etc and check your individual browser preferences

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

CSS NAVIGATION BAR

Many a time when there is a need to go for a navigation bar we simply remember javascript and write a functionality based on mouse onhouver property, we achieve the functionality but sometimes when javascript is disabled on clients computer then what the function never fires but in CSS we have functionality called hover will always run independent of javascript and writing is also very simple here is example how we can achieve it.

Step 1: Create an html file copy and paste the code below.

xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />

<title>Strip Menu Model</title>

<style type=”text/css”>

.stripboxmenu {padding: 0; width: 100%; /* width of the menu strip, 100% will extend to the full resolution of the screen */

border-top: 5px solid #000033; /*specify the color strip width,color */

background: transparent;

}

.stripboxmenu ul {margin:0;

margin-left: 80px; /*space between first menu item and left edge*/

padding: 0; /*Spacing between the strip and menu boxes*/

list-style: none;

}

.stripboxmenu li {display: inline;

margin: 2 2px 2 2;

padding: 0;

text-transform:uppercase;

}

.stripboxmenu a {

float: left;

display: block;

font: bold 12px Arial; /* Specify the font attributes like font style, boldness */

color: black; /* specify the color of the font */

text-decoration: none; /* remove the default underline of the anchor tag */

margin: 2 2px 2 2; /*Margin between each menu item, you can increase the spacing between the menus by adjusting the attributes*/

padding: 7px 15px 7px 15px; /*with this we can increase the width of the menu item (blue background)*/

background-color: lightblue; /*menu color*/

border-bottom: 9px solid white;

}

.stripboxmenu a:hover{

background-color: #f98a10; /*Mouseover color*/

padding-top: 20px; /*increase the height of the menu on mouseover using padding attribute */

border-bottom-color: #f98a10;

color: white;

}

/*Specify the style for current tab*/

.stripboxmenu .current a{

background-color: #000000;

padding-top: 12px;

border-bottom-color: #000000;

color: white;

}

</style>

</head>

<body>

<div>

<ul>

<li><a href=”#” title=”home”>Home</a></li>

<li><a href=”#” title=”what we do”>What We Do</a></li>

<li><a href=”#” title=”services”>Services</a></li>

<li><a href=”#” title=”clients”>Clients</a></li>

<li><a href=”#” title=”contact us”>Contact Us</a></li>

</ul>

</div>

<br style=”clear: both;” />

</body>

</html>

Step 2: now run the file in any browser it will look like this

As the html is rendered as li and anchor link inside it we can have many li inside another li to have sub sub menus.

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

ASP – RESPONSE and REQUEST OBJECT

Response Object

The ASP Response object is used to send output to the user from the server. Its collections, properties, and methods are described below:

Collections

Collection Description
Cookies Sets a cookie value. If the cookie does not exist, it will be created, and take the value that is specified

Properties

Property Description
Buffer Specifies whether to buffer the page output or not
CacheControl Sets whether a proxy server can cache the output generated by ASP or not
Charset Appends the name of a character-set to the content-type header in the Response object
ContentType Sets the HTTP content type for the Response object
Expires Sets how long (in minutes) a page will be cached on a browser before it expires
ExpiresAbsolute Sets a date and time when a page cached on a browser will expire
IsClientConnected Indicates if the client has disconnected from the server
Pics Appends a value to the PICS label response header
Status Specifies the value of the status line returned by the server

Methods

Method Description
AddHeader Adds a new HTTP header and a value to the HTTP response
AppendToLog Adds a string to the end of the server log entry
BinaryWrite Writes data directly to the output without any character conversion
Clear Clears any buffered HTML output
End Stops processing a script, and returns the current result
Flush Sends buffered HTML output immediately
Redirect Redirects the user to a different URL
Write Writes a specified string to the output

The ASP Request object is used to get information from the user.

Request Object

When a browser asks for a page from a server, it is called a request. The ASP Request object is used to get information from the user. Its collections, properties, and methods are described below:

Collections

Collection Description
ClientCertificate Contains all the field values stored in the client certificate
Cookies Contains all the cookie values sent in a HTTP request
Form Contains all the form (input) values from a form that uses the post method
QueryString Contains all the variable values in a HTTP query string
ServerVariables Contains all the server variable values

Properties

Property Description
TotalBytes Returns the total number of bytes the client sent in the body of the request

Methods

Method Description
BinaryRead Retrieves the data sent to the server from the client as part of a post request and stores it in a safe array

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

 

ASP – Lifetime of Variables

A variable declared inside a procedure is created and destroyed every time the procedure is executed. No scripts outside the procedure can access or change the variable.

To declare variables accessible to more than one ASP file, declare them as session variables or application variables.

Session Variables

Session variables are used to store information about ONE single user, and are available to all pages in one application. Typically information stored in session variables are name, id, and preferences.

Application Variables

Application variables are also available to all pages in one application. Application variables are used to store information about ALL users in a specific application.

Procedures

The ASP source code can contain procedures and functions:

<html>

<head>

<%

sub vbproc(num1,num2)

response.write(num1*num2)

end sub

%>

</head>

<body>

Result:

</body>

</html>

Insert the <%@ language=”language” %> line above the tag to write procedures or functions in another scripting language than default:

<%@ language=”javascript” %>

<html>

<head>

<%

function jsproc(num1,num2)

{

Response.Write(num1*num2)

}

%>

</head>

<body>

Result:

</body>

</html>

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

ASP.NET Web Server Controls

This Post shows  How to Use Server Controls in Asp.Net Web Pages

ASP.NET Server controls
1) Html Server Controls (HtmlAnchor Control, HtmlButton Control, HtmlForm Control, HtmlImage Control…).
2) Web Sever Controls
• Basic Web Controls (Button, Checkbox, Hyperlink…).

• Validation Controls (RequiredFieldValidator Control, RangeValidator Control, CompareValidator Control..).

• List Controls (ListBox, CheckBox, RadioButtonList, Repeater, DataList, GridView, DropDownList, ListView).

• Rich Controls (AdRotator, Calender).
• User Controls.
• Custom Controls.

Table comparison is the easiest way to quickly decide which data list control is best for your specific project requirements.

Always go for the control that provides the built in feature for your needs. But In most real-life examples, you would need to write some amount of custom code to make sure that the resulting Web page shows information in the most desirable format. When choosing the control look for performance, ease of use and maintainability effects to determine the best practice.

Real time Scenarios.

Case 1: Displaying 100 records from the database using DataBind().

Comparing performance differences between the data grid, data list, and repeater controls.

Option 1 is the repeater solution, option 2 is the data list solution, and option 3 is the data grid solution.

Of the three solutions, recommended is that you consider the data list control as your first choice. Look at the data grid control only when you discover that data list doesn’t provide a desired built-in feature. Similarly, you should use the repeater only when the data list control is too slow for your needs.

Details

  1. Datagrid is most restrictive as regards to customization followed by DataList and finally Repeater is the most customizable.
  2. Datagrid has built in paging, sorting and editing capabilities which are not there with the other two controls. So if you want users to sort / page / edit data, datagrid is the natural choice.
  3. DataList and repeater have better performance than datagrid. So if performance is a major concern, for example, a site with large number of concurrent visitors, then you could think of datalist or repeater.
  4. Repeater is the most customizable. It allows you to create structures like nested lists, for example.
    A datagrid row displays one record from the data source, while a datalist row can display more than one records (set by RepeatColumns property).
  5. Datagrid and Datalist are derived from WebControl while Repeater is not, and so does not have the stylistic properties of web controls.
  6. Datalist can display more then one record in a single row. While Repeater can’t.
  7. Datalist has a property called repeat. Direction = vertical/horizontal. (This is of great help in designing layouts). This is not there in Datagrid.
    1. With same template and same data set, Repeater usually works faster of DataList or GridView controls. This is mostly because of DataReader class, which is used for read only access. DataReader is faster than DataSet or DataTable classes commonly used with GridView.
    2. DataList has RepeatDirection, RepeatColumns and RepeatLayout properties, which are unique for DataList control. These properties are useful when you need to create presentation with more than one record per row, like image gallery, product catalog etc.

10. Common problem when using GridView control could be large ViewState which makes page loads slower and requires more bandwidth. This could be insignificantly on low traffic website, but keep in mind that for each second while the page loads, the percentage of visitors will become impatient and leave website. Also, massive view state is not good for SEO (search engine optimization).

11. One more problem is using of default pager on large tables or high traffic websites. If default paging is used, GridView will load complete dataset in memory, which descreases website’s performances.

12. Since Repeater control does not generate additional HTML, it also can be used to generate RSS feeds.

Summary

Thus, we have understood the various databound controls and its advantages and disadvantages which will help us to choose the right control for our need.

To sum up,

  • Choose Gridview if your requirement is displaying tabular data. For example, a search result page where the customer expects a sorting clicking on the header. Also, it is very easy to provide custom paging with GridView when we use ObjectDataSource control.
  • Choose between DataList and Repeater control for flow/tiled layout. DataList control will help you in providing editing the data where Repeater will not.
  • If you use ASP.Net 3.5, then ListView control will satisfy almost all of your need in terms of the layout of the data display. This control is most flexible and versatile that can fit all your need.

Don’t forget to switch off the viewstate if your need is only display to get better performance.

1. If your Data access operations is mainly fetching and displaying the records and doesnt involve insert/update/delete statements and other manipulations (forward only, read only) actions, go for the DataReader.
DataReader offers a forward only read stream of access to the records. It is very useful in cases where we just grab the data from the database to display in DataGrid, Label and other Webcontrols.
However, DataReader requires the connection with the database open until its operation is completed.

2. If your Data access operations extend to as simple as an Insert/Update/Delete statement to as complex as using it as a return type from a web service, go for the DataSet. The DataSet has the following advantages.

i. Complex Data type supporting numerous methods such as ReadXML which reads new XML data to form a dataset, WriteXML which provides an XML format of the existing data, etc.,
ii. Works on the disconnected architecutre i.e. The connection doesnt need to be on for the DataSet to perform the manipulations and other actions and is required only at the time of Updating the records to the Database Table.

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )