Dataset
和
datagridview
的使用示例
主要参考
使用SQL Server 的pubs数据库中的authors表
1.
创建
Windows
窗体
2.
配置数据集
创建数据连接和数据适配器
从“工具箱”的“数据”选项卡中,将
OleDbDataAdapter
对象拖到窗体上。
点击右键-“数据适配器配置向导”
-创建以下
SQL
语句:
SELECT au_id, au_lname, au_fname, city, state, phone, contract
FROM authors
3.
生成数据集
选择“新建”选项,将数据集命名为
dsAuthors
。
在“选择要添加到数据集中的表”下面的列表中,应选择“
authors
”表。
4.
添加
datagridview
控件
绑定控件:
在
DataSource
属性中,选择
DsAuthors1
(或
dsAuthors1
)作为数据源。不选择
DsAuthors1.Authors
(或
dsAuthors1.Authors
)。
在
DataMember
属性中选择“
authors
”。
设置这两个属性会将
DsAuthors1
数据集内的
authors
数据表绑定到网格。
这一步要尤其注意,只有在
datagridview
的
DataMember
属性中选择表后,数据才能最后加载显示。
5.
填充
datagridview
控件
(
1
)添加
button
,加载数据
private void btnUpdate_Click(object sender, System.EventArgs e)
{
oleDbDataAdapter1.Update(dsAuthors1);
MessageBox.Show("Database updated!");
}
(
2
)添加
button
,更新数据
private void btnLoad_Click(object sender, System.EventArgs e)
{
dsAuthors1.Clear();
oleDbDataAdapter1.Fill(dsAuthors1);
}
6.
测试
测试该窗体,以确保它在网格中显示作者数据,并且用户可以进行更新。
a.
SELECT au_id, au_lname, au_fname, city, state, phone, contract
FROM authors