Saturday, 18 January 2014

Use of DataView in ASP.NET.

A DataView is used for customized view of the data from a DataTable.

Example:

C#


using System.Data;
using System.Data.SqlClient;

namespace Employee
{
public partial class Emp_Details : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("server=myDB;uid=sa;pwd=password;database=master");
connection.Open();
SqlCommand command = new SqlCommand("select * from employee",connection);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = command;
DataSet ds = new DataSet();
da.Fill(ds,"employee");
DataView dv = new DataView(ds.Tables["employee"]);
dv.RowFilter = "emp_age<30";
dv.Sort = "First_Name ASC";
EmpDetails.DataSource = dv;
EmpDetails.DataBind();
connection.Close() }
}
}


VB


Imports System.Data
Imports System.Data.SqlClient

Partial Public Class Emp_Details
      Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim connetion As SqlConnection = New SqlConnection("server=myDB;uid=sa;pwd=password;database=master")
connection.Open()
Dim command As SqlCommand = New SqlCommand("select * from employee", connection)
Dim da As SqlDataAdapter = New SqlDataAdapter()
da.SelectCommand = command
Dim ds As DataSet = New DataSet()
da.Fill(ds, "employee")
Dim dv As DataView = New DataView(ds.Tables("employee"))
dv.RowFilter = "emp_age<30"
dv.Sort = "First_Name ASC"
EmpDetails.DataSource = dv
EmpDetails.DataBind()
connection.Close()
End Sub
End Class

Description

dv.RowFilter = "emp_age<30" retrieves records of those employees whose age is less than 30.
dv.Sort = "First_Name ASC" Sorts column First_Name of table employee in ascending order.
EmpDetails is a GridView ID.

No comments:

Post a Comment