ADO.NET

ADO.NET Projects

ADO.NET Project 1

ADO.NET Examples

Examples

adplus-dvertising
DataView Object
Previous Home Next

The DataView object is more than a replacement for the DataTable’s Select method . Not only are the results of the Select method on a DataTable not directly data bindable, but it is also not a very efficient method to query rows.

Creating a DataView

A DataView can be created using any of the three constructor overloads it supports. The first constructor overload allows you to create a DataView but not specify any information

DataView  dv = new DataView() ;

The second constructor directly ties the DataView to a DataTable

DataView dv = new DataView(TableName) ;

The third and final constructor of DataViews allows you to specify all that information in one line of code.

DataView dv =new DataView(
EmpTable, "EmpID = 1001", 
"EmpName", DataViewRowState.Unchanged);
Example of DataView Object
private void DataViewexample()
{
// Create one DataTable with one column.
DataTable tb = new DataTable("student");
DataColumn dc = new DataColumn("stuentname",
Type.GetType("System.String"));
table.Columns.Add(colItem);

// Add five items.
DataRow NewRow;
for(int i = 0; i <5; i++)
{
NewRow = table.NewRow();
NewRow["studentname"] = "studentname " + i;
table.Rows.Add(NewRow);
}
// Change the values in the table.
table.Rows[0]["studentname"]="Ashish";
table.Rows[1]["studentname"] = "Aditya";
tb.AcceptChanges();
// Create two DataView objects with the same table.
DataView firstView = new DataView(table);
DataView secondView = new DataView(table);
// Print current table values.
PrintTableOrView(table,"Current Values in Table");
// Set first DataView to show only modified 
// versions of original rows.
firstView.RowStateFilter=DataViewRowState.ModifiedOriginal;
// Print values.   
PrinSTDtTableOrView(firstView,"First DataView: ModifiedOriginal");
// Add one New row to the second view.
DataRowView rowView;
rowView=secondView.AddNew();
rowView["studentname"] = "Anil";
// Set second DataView to show modified versions of 
// current rows, or New rows.
secondView.RowStateFilter=DataViewRowState.ModifiedCurrent 
| DataViewRowState.Added;
// Print modified and Added rows.
PrintTableOrView(secondView, 
"Second DataView: ModifiedCurrent | Added");
}
private void PrintSTDTableOrView(DataTable table, string s)
{
// This function prints values in the table or DataView.
Console.WriteLine("\n" + s);
for(int i = 0; i<table.Rows.Count;i++)
{
Console.WriteLine("\table" + table.Rows[i]["studentname"]);
}
Console.WriteLine();
}
private void PrintSTDTableOrView(DataView view, string label)
{
// This overload prints values in the table or DataView.
Console.WriteLine("\n" + s);
for(int i = 0; i<view.Count;i++)
{
Console.WriteLine("\table" + view[i][""studentname"]);
}
Console.WriteLine();
}
Previous Home Next