以前使用Visual Studio2003的时候,有个Datagrid控件,现在该用Visual Studio2005了,控件也发生了一些改变.现在Datagrid控件现在也摇身变成了Dataview了.不过变了功能更强大了。但是一些基本的东西还是大体一致的。今天我们就来说一下Dataview控件的使用。
Dataview控件主要是用来实现数据的Select、Insert、Delete、Update功能。现在假定我们存在两个表:基本信息(基本信息包含有ID、姓名、性别、年龄4个字段)、学生成绩(ID、语文、数学、英语 4个字段)。
首先设置Dataview的AutoGenerateColumns属性为false,并插入以下代码:
1
SqlConnection cnn
=
new
SqlConnection(ConfigurationManager.ConnectionStrings[
"
ServerConnectionString
"
]).ConnectionString;
2
SqlCommand da
=
new
SqlCommand(
"
select * from 基本信息 W,学生成绩 S where W.ID=S.ID
"
,cnn);
3
GridView1.DataSource
=
ds.Tables[
"
student
"
];
4
GridView1.DataBind();
5 Data_Bind();
这样才算真正意义上实现了Dataview的数据绑定。
2
3
4
5 Data_Bind();
其中ServerConnectionString是连接字符串名。需要在web.config中插入以下语句.
1
<
appSettings
/>
2
<
connectionStrings
>
3
<
add name
=
"
ServerConnectionString
"
connectionString
=
"
Data Source=172.16.1.251;Initial Catalog=qcreport;User ID=sa;Password=fedma13
"
4
providerName
=
"
System.Data.SqlClient
"
/>
5
</
connectionStrings
>
2
3
4
5
好了,对于数据的显示我们已经完成了。下面我们说一下关于排序和分页。
我们知道.net提供了强大的分页和排序功能。我们只需要写两行代码就可以实现排序和分页功能。
首先设置Dataview的属性AllowPaging 和AllowSorting为true。然后写下如下代码:
1
protected
void
GridView1_PageIndexChanging(
object
sender, GridViewPageEventArgs e)
2
{
3
GridView1.PageIndex = e.NewPageIndex;
4
data_bind();
5
}
6
protected
void
GridView1_Sorting(
object
sender, GridViewSortEventArgs e)
7
{
8
GridView1.Sorting = e.SortExpression;
9
data_bind();
10
}
2
3
4
5
6
7
8
9
10
好了,我们现在就可以对我们写的代码来进行测试了。