在C#中调用视图
在C#中调用视图
视图的调用方法与表的调用是一样的,由于视图是虚拟表,所以一般在查询中使用。例如,在C#中调用视图中的结果时通常会用到SqlDataAdapter类,然后将视图中的结果通过Fill方法去填充结果集(DataSet)。
示例
C#中调用视图
首先创建一个用于显示查询结果的视图View_Try。然后建立一个数据操作类ClsView.cs,其中包括方法ConDB与方法dsView(用于查询视图)。当程序运行时,通过调用数据操作类(ClsView)实现对虚拟表(由t_People表和t_Class表组成)的查询操作,同时也实现了对查询结果的某一字段过滤与排序的操作,示例运行结果如图1所示。

图1 视图演示窗体
(1)ConDB方法用于建立数据库的连接。
(2)dsView方法用于查询视图(View_Try)。
ConDB方法代码如下:
public SqlConnection ConDB()
{
con = new SqlConnection("server=.;uid=sa;pwd=;database=DB_ADONET");
if (con.State == ConnectionState.Closed)
{
con.Open();
}
return con;
}
dsView方法代码如下:
public DataSet dsView(string SQLWhere)
{
string SQL = "select * from View_Try";
SQL += SQLWhere;
try
{
DataSet ds = new DataSet();
da = new SqlDataAdapter(SQL, ConDB());
da.Fill(ds);
return ds;
}
catch
{
return null;
}
}
单击【查询】按钮,将会生成SQL语句,然后将SQL语句传递给dsView方法,实现信息查询。【查询】按钮的Click事件代码如下:
private void button1_Click(object sender, EventArgs e)
{
StringBuilder strSQLWhere = new StringBuilder();
strSQLWhere.Append(" where ");
strSQLWhere.Append(" 编号like '%" + this.textBox1.Text.Trim().ToString()
+ "%'
and");
strSQLWhere.Append(" 班级like '%" + this.textBox2.Text.Trim().ToString()
+ "%'
and");
strSQLWhere.Append(" 人数like '%" + this.textBox3.Text.Trim().ToString()
+ "%'
and");
strSQLWhere.Append(" 姓名like '%" + this.textBox4.Text.Trim().ToString()
+ "%'
and");
strSQLWhere.Append(" 性别like '%" + this.textBox5.Text.Trim().ToString()
+ "%'");
ClsDB.ClsView CV = new OptDB.ClsDB.ClsView();
this.dataGridView1.DataSource=CV.dsView( strSQLWhere.ToString()).Tables[0];
}
ChangeRowFilter方法用于实现对数据源进行筛选,代码如下:
private void ChangeRowFilter(string str)
{
if (this.textBox6.Text.Trim().ToString() != "")
{
DataTable custDV = (DataTable)this.dataGridView1.DataSource;
if (custDV != null)
{
custDV.DefaultView.RowFilter = "人数" + str;
this.dataGridView1.DataSource = custDV;
}
else
{
MessageBox.Show("无操作数据");
}
}
}
SortRow方法用于实现对数据源进行排序,代码如下:
private void SortRow(string str)
{
DataTable custDV = (DataTable)this.dataGridView1.DataSource;
if (custDV != null)
{
custDV.DefaultView.Sort = " 编号"+str;
this.dataGridView1.DataSource = custDV;
}
else
{
MessageBox.Show("无操作数据");
}
}
单击【过滤】按钮,调用ChangeRowFilter方法实现对数据源的过滤功能。【过滤】按钮的Click事件代码如下:
private void button2_Click(object sender, EventArgs e)
{
this.ChangeRowFilter(this.textBox6.Text.Trim().ToString());
}
单击【排序】按钮,调用SortRow方法实现对数据源的排序功能。【排序】按钮的Click事件代码如下:
private void button3_Click(object sender, EventArgs e)
{
string strState;
if (this.radioButton1.Checked)
strState = "asc";
else
strState = "desc";
SortRow(strState);
}
完整程序代码如下:
★ ★★★★FrmView.cs窗体代码文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace _3_06
{
public partial class FrmView : Form
{
public FrmView()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)