C#创建DataSet对象详细介绍

C#语言有很多值得学习的地方,这里我们主要介绍C#创建DataSet对象,包括介绍在视图菜单上,选择工具箱以显示“工具箱”等方面。

成都创新互联从2013年成立,是专业互联网技术服务公司,拥有项目网站设计、成都网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元大方做网站,已为上家服务,为大方各地企业和个人服务,联系电话:13518219792

本文说明如何C#创建DataSet对象,以及如何使用WriteXML方法将该对象包含的数据导出到 XML 文件中。生成的 XML 文件可以直接在 Excel 中打开。为便于说明,使用 Jet OLEDB 提供程序从 Microsoft Access Northwind 示例数据库C#创建DataSet对象。但是,类似的代码可与您使用 Visual C#创建DataSet对象一起使用。

1. 启动 Microsoft Visual Studio .NET。在文件菜单上,单击新建,然后单击项目。从 Visual C# 项目类型中选择Windows 应用程序。默认情况下创建 Form1。

2. 在视图菜单上,选择工具箱以显示“工具箱”,然后向 Form1 中添加一个按钮。

3. 双击Button1。将出现该窗体的代码窗口。

4. 将下面的using 指令添加到 Form1.cs 顶部:

 
 
 
  1. using System.Data.OleDb;  
  2. using System.Xml; 

5.将下面的私有成员变量添加到 Form1 类中:

 
 
 
  1. private string strConn =Provider=Microsoft.Jet.OLEDB.4.0;  
  2. Data Source= + C:\\Program Files\\Microsoft Office
  3. \\Office10\\Samples\\ + Northwind.mdb;; 

注意:您可能需要修改连接字符串中 Northwind.mdb 的路径,以便与您安装的位置相匹配。

6.在button1_Click 处理程序中添加以下代码:

 
 
 
  1. //Connect to the data source.OleDbConnection objConn = 
    new OleDbConnection (strConn);  
  2. try{  
  3. objConn.Open();  
  4. //Fill a dataset with records from the Customers table.OleDbCommand objCmd = 
    new OleDbCommand(Select CustomerID, CompanyName, ContactName+ Country, 
    Phone from Customers, objConn);  
  5. OleDbDataAdapter objAdapter = new OleDbDataAdapter();  
  6. objAdapter.SelectCommand = objCmd;  
  7. DataSet objDataset = new DataSet();  
  8. objAdapter.Fill(objDataset);  
  9. //Create the FileStream to write with.System.IO.FileStream fs = 
    new System.IO.FileStream(C:\\Customers.xml,System.IO.FileMode.Create);  
  10. //Create an XmlTextWriter for the FileStream. System.Xml.XmlTextWriter xtw = 
    new System.Xml.XmlTextWriter(fs, System.Text.Encoding.Unicode);  
  11. //Add processing instructions to the beginning of the XML file, one  
  12. //of which indicates a style sheet.xtw.WriteProcessingInstruction
    (xml, version='1.0');  
  13. //xtw.WriteProcessingInstruction(xml-stylesheet,  
  14. // type='text/xsl' href='customers.xsl');  
  15. //Write the XML from the dataset to the file.objDataset.WriteXml(xtw);  
  16. xtw.Close();  
  17. //Close the database connection.  
  18. objConn.Close();  
  19. }  
  20. catch (System.Exception ex)  
  21. {  
  22. MessageBox.Show(ex.Message);  

【编辑推荐】

  1. C#使用sqlserver存储浅析
  2. 由C++转向C#简单介绍
  3. C# oledbconnection方法浅谈
  4. 数据库常用C#代码概述
  5. C#调用ImOK学习笔记

分享文章:C#创建DataSet对象详细介绍
网站URL:http://www.hantingmc.com/qtweb/news4/35504.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联