DataView is used
for customized view of data of DataTable. Using DataView we can apply search,
Filter and sorting on run time without changing our sql query
// Here is the
example
//.aspx page
code
<%@ Page Language="C#"
AutoEventWireup="true"
EnableViewState="true"
CodeFile="Data_View.aspx.cs"
Inherits="Data_View"
%>
DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
>
<head runat="server">
<title>Data View
Exampletitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtSearch" runat="server">asp:TextBox> <asp:Button ID="btnSearch"
runat="server"
Text="Search"
OnClick="btnSearch_Click"
/>
<asp:GridView ID="gvCustDetails" EnableViewState="true" runat="server" AutoGenerateColumns="false" Width="80%" HorizontalAlign="Center">
<Columns>
<asp:BoundField DataField="empName" HeaderText="Name" />
<asp:BoundField DataField="salary" HeaderText="Salary" />
Columns>
asp:GridView>
div>
form>
body>
html>
Note : you need
to set page attribute EnableViewState="true" to
active View State
//.aspx.cs page
code
private void BindGridView()
{
DataTable dt = new DataTable();
if
(ViewState["Vwdt"] == null)
{
SqlCommand
cmd = new SqlCommand("select * from EmployeeMaster", dbCon);
dbCon.Open();
SqlDataAdapter
da = new SqlDataAdapter(cmd);
da.Fill(dt);
ViewState["Vwdt"]
= dt;
}
dt = (DataTable)ViewState["Vwdt"];
DataView
dv = new DataView(dt);
string
strSearchText = txtSearch.Text;
//on search
button click it will check the search text and filter accordingly
if
(strSearchText != "")
{
dv.RowFilter = "empName like '%" + strSearchText + "%'";
}
dv.Sort = "empName
ASC";
gvCustDetails.DataSource = dv;
gvCustDetails.DataBind();
}
protected void btnSearch_Click(object
sender, EventArgs e)
{
BindGridView();
}
Comments