Entries Tagged as ''

ASP.NET Tutorial - ADO.NET Working with SQL server database

ADO.NET provides an API for accessing database systems according to the programs. ADO.NET was created for the .NET Framework and it can be said that they are next generation of Active Data Objects (ADO). The .NET Framework contains several namespaces and classes, which are devoted to database accesses. Microsoft has created separate namespaces that are optimized for working with different data providers (different types of databases). Before starting this topic, the user should have good knowledge of Databases such as MS Access and SQL Server or Oracle.

The following data provides specific namespaces that are included with ADO.NET:

System.Data.SqlClient

Contains classes for connecting to Microsoft SQL Server version 7.0 or higher

System.Data.OleDb

Contains classes for connecting to a data source that has an OLE DB provider

System.Data.Odbc

Contains classes for connecting to a data source that has an ODBC driver

System.Data.OracleClient

Contains classes for connecting to an Oracle database server

The System. Data. SqlClient namespace includes the following three classes:

* SqlConnection
* SqlCommand
* SqlDataReader

You will use these classes very often when you plan to build your ASP.NET application with Microsoft SQL Server (version 7.0 or higher). These classes enable you to execute SQL state­ments and retrieve data quickly from a database query.

The SqlConnection class represents an open connection to a Microsoft SQL Server data­base.

The SqlCommand class represents a SQL statement or stored procedure.

Finally, the SqlDataReader class represents the results from a database query.

The next section of this chapter goes into the details of using each of these classes.

The first group of classes, from the System.Data.SqlClient namespace, works only with Microsoft SQL Server. If you want to work with another type of database, such as an Access or Oracle database, you have to use the classes from one of the other data provider-specific namespaces.

For example, if you want to connect to a Microsoft Access database, then you’ll need to use the classes from the System. Data. OleDb namespace. The System.Data.OleDb name­space includes the following classes:

* OleDbConnection
* OleDbCommand
* OleDbDataReader

It has to be noted that these classes have the same names as the ones in the previous group, except that these class names start with OleDb rather than SQL.

The OleDbConnection class represents an open database connection to a database.

The OleDbCommand class represents a SQL statement or stored procedure.

The OleDbReader class represents the results from a database query.

Performing Common Database Tasks

In the following sections, the method of performing common database tasks using ADO.NET will be discussed. First, you will create and open a database connection.

Second, you will retrieve and display database records, add new database records, update existing database records, and delete database records.

Third, you will perform all these tasks using classes from both the System.Data.SqlClient and System.Data.OleDb namespaces.

When you work with SQL Server, you need to import the System.Data.SqlClient namespace by adding the follow­ing page directive at the top of your ASP.NET page:

<%@ Import Namespace=”System.Data.SqlClient” %>

When working with other databases, such as Microsoft Access or Oracle databases, you need to import the System.Data.OleDb namespace by using the following page directive:

<% @ Import Namespace=”System.Data.OleDb” %>
How to Open a Database Connection ?

The following Example would show how to create and open a connection for a Microsoft SQL Server databases.
Example 17 OpenSqlConnection.aspx

<%@ Import Namespace=”System.Data.SqlClient” %>
<Script Runat=”Server”>Sub Page_Load

Dim conNorthwind As SqlConnection

conNorthwind=NewSqlConnection(”Server=localhost;uid=sa;pwd=secret;database= Northwind” )

conPubs. Open ()

End Sub

</Script>
Connection has been opened!

Firstly the System.Data.OleDb namespace is imported at the top of the page rather in the System. Data.SqlClient namespace.

Secondly,Instead of SQL classes OleDb classes are used in all the statements.

After you finish displaying the records from a DataReader, be sure to explicitly close it (using the Close () method).

Retrieving a Single Database Record

The developers generally need a single record from a database. Therefore it is very important to know how to retrieve it. For example, given a username you might have to look up someone’s password or retrieve a phone number for John from a database table.

Another common situation which requires retrieval of single database record is aggre­gate functions like MAX (), MIN (), COUNT () etc.

The previous section dealt with the use of a DataReader representing the results of a database query. But if there is a need, to retrieve a single result from a query, the ExecuteScalar () method is more efficient than the ExecuteReader () method, as it requires less coding.

The following example counts the no. of records from Employees table. We use the ExecuteScalar () method to retrieve and display the value of the SQL Count (*) aggregate function.

Example 21 SqlExecuteScalarCount.aspx

<%@ Import Namespace=”System.Data.SqlClient” %>

<Script Runat=”Server”>

Sub Page_Load

Dim conNorthwind As SqlConnection

Dim cmdSelectCount As SqlCommand

conNorthwind = New SqlConnection( “Server=localhost;UID=sa;PWD=secret;database=Northwind” )

conNorthwind.Open()

cmdSelectCount = New SqlCommand( “Select Count(*) From Employees”, conNorthwind )

lblEmp.Text = cmdSelectCount.ExecuteScalar()

conNorthwind.Close()

End Sub

</Script>

<html>

<body>

There are

<asp:Label

ID=”lblEmp”

Runat=”Server” />

Employees in this Table

</body>

</html>


Understanding ASP.NET Validation Controls

ASP.NET validation controls provide an easy-to-use but powerful mechanism of ensuring that data is entered correctly on the forms. There are 6 validation controls included in the ASP.NET 2.0 and ASP.NET 3.5 versions


<script type=”text/javascript”>
function ValidateCheckBox()
{

}
</script>
<asp:Button ID=”btnPost” runat=”server” Text=”Post”
OnClientClick=”javascript:return ValidateCheckBox();”  OnClick=”btnPost_Click” />

In this article, let us see some tips and tricks that can be applied to the validation controls. This article is for beginner and intermediate users who have been using validation controls. There is something for everyone!!
Tip 1: Always use Page.IsValid before submitting data. Apart from the other benefits, using it prevents submitting data from old browsers that do not support javascript.
Tip 2: The display property for the ASP.NET validation controls has 3 settings: None, Static(default), and Dynamic. ‘Static outputs HTML code (related to error) at all times even when no error has occurred. So when there is more than one validation control placed next to the field, the first validation control occupies screen space even when there is no error. In case the second validation control fires an error message, the message is pushed away from the control since the first validation control is occupying screen space.
Set the ‘display’ property of a validation control to ‘Dynamic’. This property renders the error message with the attribute display:none; It helps you to display the error message next to the control .
Tip 3: To prevent validation to occur on the click of the Cancel button, set the ‘CausesValidation’ property to false
<asp:Button ID=”btnCancel” Runat=”server” CausesValidation=”False” Text=”Cancel” />
Tip 4: Use the ‘InitialValue’ property of the RequiredFieldValidator to validate controls like combobox which have a default value.
For eg: If your combobox has a default item called “–Select –“ and you want that the user should select a value other than the default value before submitting the form, then set the ‘InitialValue’ property of the RequiredFieldValidator to “–Select–“.
<asp:DropDownList ID=”DropDownList1″ runat=”server”>
<asp:ListItem Value=”–Select–” />
<asp:ListItem Value=”Item1″ />
<asp:ListItem Value=”Item2″ />
<asp:ListItem Value=”Item3″ />
</asp:DropDownList>
<asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server” ErrorMessage=”RequiredFieldValidator” ControlToValidate=”DropDownList1″ InitialValue=”–Select–”></asp:RequiredFieldValidator>
Tip 5: A RegularExpressionValidator can be used to handle string patterns. For eg: A Name textbox that should accept a maximum of 30 characters with only alphabets, space, fullstop(.) and a ‘(apostrophe). A regularexpression like ‘^([a-zA-z.'\s]{2,30})$’ does the trick.
However when you are using Localization and using a language like Arabic, you have to often provide for validating characters in a different dialect. You can solve this using the following technique:
- In the Resource.resx file, create a resourcekey called ValidName giving it a value of ^([a-zA-z.'\s]{2,30})$
- In the Resource.ar-EG.resx file, use the same key but with a diff value ^([
\u0600-\u06FF.'\s]{2,30})$
Use it in your page using the following way. Observe the bold text:

<asp:RegularExpressionValidatorID=’regEVFname’ runat=’server’ControlToValidate
=’txtName’
Display=’Dynamic’ErrorMessage
=’Invalid’
ValidationExpression
=’<%$ Resources:Resource, ValidName %>SetFocusOnError=’True’></asp:RegularExpressionValidator>

When the user selects English, he can enter only A-Za-z. Similarly for Arabic, he can enter only the Arabic characters and not English.
Tip 6: The validation controls provide both Server and Client Side validation. To turn off client-side validation, set the ‘EnableClientScript = false’
<asp:RequiredFieldValidator ID=”RequiredFieldValidator2″ Runat=”server”
Text=”Error” ControlToValidate=”TextBox1″ EnableClientScript=”false”/>
Tip 7: Use CompareValidator to validate date with format of “dd/MM/yyyy”.
The validator uses the CultureInfo object of the thread to determine date format. So what you need to do is to set the desired culture format in the Page directive
<%@ Page culture=”your culture” %>
This tip was shared by PeterBlum in the asp.net forums. By the way, Peter has an amazing suite of data entry and validation controls on his site at a reasonable price.
Tip 8: Instead of the textual error message, you can even add an image or sound to your validator control. The Text and Error Message property accepts HTML tags.
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<br />
<asp:RequiredFieldValidator ControlToValidate=”TextBox1″ EnableClientScript=”false” ID=”RequiredFieldValidator1″ runat=”server” Text=”<bgsound src=’C:\Windows\Media\Windows Error.wav’>”></asp:RequiredFieldValidator>
Just make sure that the EnableClientScript=”false” when you want a sound instead of a text message.
Tip 9: If you have two set of forms (eg: Login and Registration) in a single page and want to keep the validation of the two groups separate, use ‘ValidationGroups’. All you need to do, is to specify a common group name for a set of controls that you want to validate separately.
<div>
<asp:TextBox ID=”TextBox1″ ValidationGroup=”Group1″ runat=”server”></asp:TextBox>
<br />
<asp:RequiredFieldValidator ControlToValidate=”TextBox1″ ValidationGroup=”Group1″ ID=”RequiredFieldValidator1″ runat=”server” Text=”Error”></asp:RequiredFieldValidator>
<asp:Button ID=”Button1″ runat=”server” ValidationGroup=”Group1″ Text=”Button” />
</div>
<br />
<br />
<div>
<asp:TextBox ID=”TextBox2″ ValidationGroup=”Group2″ runat=”server”></asp:TextBox>
<br />
<asp:RequiredFieldValidator ControlToValidate=”TextBox1″ ValidationGroup=”Group2″ EnableClientScript=”false” ID=”RequiredFieldValidator2″ runat=”server” Text=”Error”></asp:RequiredFieldValidator>
<asp:Button ID=”Button2″ runat=”server” ValidationGroup=”Group2″ Text=”Button” />
</div>
Tip 10: Other validator controls like CompareValidator, RangeValidator etc. do not provide a way to detect if the field is blank or required. The only way is to do this is to add a RequiredFieldValidator along with the other validator controls.
However one exception being the CustomValidator which provides a property called ‘ValidateEmptyText’. Just set it to true and it validates the field even if the user has kept the field blank.
Tip 11: If you want your validation error message to appear in the ‘ValidationSummary‘ control, then set the ‘ErrorMessage’ property on that validation control. Also, setting ‘ShowMessageBox = true’ on the ValidationSummary enables you to display a popup alert.
Tip 12: In order to create a CustomValidationControl you have to derive from the ‘BaseValidator’ class and implement the ‘EvaluateIsValid()’ method.
Tip 13: In case of an error, the validation controls allow you to set focus on a control in error using the ‘SetFocusOnError’ property.
<asp:RequiredFieldValidator SetFocusOnError=”true” ControlToValidate=”TextBox1″ ID=”RequiredFieldValidator1″ runat=”server” Text=”Error!!”></asp:RequiredFieldValidator>


Validation Control in asp.net

There are two types of validations like client-side and server-side. While client side validations can be performed using JavaScript and VBScript, server side validations can be achieved via classic ASP. The biggest problem with these languages and technologies is that you have to write lengthy code to perform a simple task. Since, VBScript won’t work with Netscape browser, you cannot perform client-side validations using this language. You have to learn JavaScript or Classic ASP to perform validations.
With ASP.NET, these difficulties are eliminated. ASP.NET provides its own built-in controls for validations. You can easily place controls and write codes by using a text editor like Notepad or an IDE like Visual Studio .NET. Moreover, ASP.NET supports C#, Visual Basic .NET, and any other language in the Microsoft .NET family. ASP.NET provides six types of validation controls. They are

  • CompareValidator
  • CustomValidator
  • RangeValidator
  • RegularExpressionValidator
  • RequiredFieldValidator
  • ValidationSummary

Each of these above controls can be linked to .NET Web Form controls like TextBox, Dropdownbox, ListBoxes etc. Even though there are wide ranges of controls for validation, it is up to you to decide upon which control to use. It also depends up on your project needs. In this first part of this series, you will learn the application of first three controls with code listings using VB .NET and C#.

CompareValidator

As the name suggests, this control is used to compare the values of one control with another control. The comparison is done with the help of textboxes. The CompareValidator control has two important properties namely, Operator and Type. The Operator property is mainly used as a basis of comparison between two values (GreaterThan, LessThan, Equal, NotEqual etc) and Type property indicates the data type of the values like Integer, string etc.

To illustrate, copy or enter the code in Listing 1 and save the file with extension .aspx under the Inetpub/wwwroot directory. Be sure to install .NET Framework SDK or Visual Studio .NET before attempting this work.

CustomValidator

With the help of the Custom Validator control, you can write your own functions and use them for performing validations in Web Forms. These functions are similar to that of JavaScript and VBScript functions.

<script runat=”server”>
Sub ServerValidate (sender As Object, _
value As ServerValidateEventArgs)
Dim num As Int32 = Int32.Parse(value.Value)
If num Mod 2 = 0 Then
value.IsValid = True
Exit Sub
End If
value.IsValid = False
End Sub
</script>


<script runat="server">
void Page_Load() {
lblMessage.Text = "Hello World";
}
</script>

Finally, you should integrate the above function with a WebForm control via ClientValidationFunction and ServerValidationFunction properties as shown in listing shown below:

<asp:TextBox id=”Text1″ runat=”server” />
<asp:CustomValidator id=”CustomValidator1″ runat=”server”
ControlToValidate=”Text1″ OnServerValidate=”ServerValidate”
Display=”Static” Font-Name=”verdana” Font-Size=”8pt” foreColor =”blue”
ErrorMessage = “Not an even number”>
</asp:CustomValidator>

You have to specify a client-side or server-side function, which will contain the logic behind the validation using the OnServerValidate property. If there are any parameters, you should also specify those with this function. You should be aware that validations performed on the client’s computer require no round trip to server and hence reducing the valuable online time of users.

RangeValidator

This control is used to accept a range of values. For instance, you can employ this validation control, if a user should have to input values within a range such as from 1 to 100 or from 50 to 150. It accepts two important properties, MinimumValue and MaximumValue, and also the Type property. The listing shown below illustrates the functionality of this control:

<%@ Page Language=”VB” %>
<script runat=”server”>
</script>
<html>
<head><title> Range Validator - VB.NET</title>
</head>
<body>
<form runat=”server”>
<p>
<asp:TextBox id=”TextBox1″ runat=”server”></asp:TextBox>
</p>
<p>
<asp:RangeValidator id=”RangeValidator1″
runat=”server”
ErrorMessage=”Please enter a number between 1 and 100″
ControlToValidate=”TextBox1″
MinimumValue=”1″ MaximumValue=”100″
Display=”Dynamic” Type=”Integer”>
</asp:RangeValidator>
</p>
</form>
</body>
</html>