65.9K
CodeProject 正在变化。 阅读更多。
Home

文章 2 - 使用 Whidbey (VB.NET) 通过 DataSet 和 DataGrid 控件显示数据

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.26/5 (21投票s)

2004年5月10日

8分钟阅读

viewsIcon

333850

本文介绍了在数据库创建后如何使用 DataSet 和 DataGrid 控件显示数据。

引言

我之前的文章介绍了使用 Visual Studio 代号 Whidbey 和 VB.NET 逐步动态创建 SQL Server 数据库、表和存储过程。我希望您已经对动态创建 SQL Server 数据库和表有了很好的入门。本文介绍了在数据库创建后如何使用 DataSetDataGrid 控件显示数据。

关于“DataTable”和“DataSet”对象

DataSet 是 ADO.NET 架构的主要组成部分。它是一组数据,是从数据源检索到的数据的内存缓存。DataSet 包含一个 DataTable 对象集合。DataTable 表示一个内存中的数据表。DataTable 的名称只有在您将“CaseSensitive”的公共属性设置为指示表中字符串比较是否区分大小写时才区分大小写。

例如,如果您将 DataTable 命名为“MyTable”,而您将表定义为“Mytable”,它将不会查找该表,因为 DataTable 名称是区分大小写的。DataSetDataView 是使用 DataTable 的两个数据对象。

DataTable 的一些公共属性如下所示:

属性 描述

  • CaseSensitive

    此属性返回一个布尔值,用于检查表名是否区分大小写。如果比较区分大小写,则返回 True;否则,返回 False。例如,如果您将 DataTable 命名为“MyTable”,而您将表定义为“Mytable”,它将不会查找该表。

    CaseSensitive 属性会影响排序、搜索和过滤中的字符串比较。

  • ChildRelations

    简单来说,它是两个表之间的关系。它就像数据库关系键,如主键、次要键等,通过一个关键字段关联两个表。

  • Columns

    数据库字段或元组。

  • 约束

    使用主键、索引等键维护表之间关系的约束。

  • DataSet

    根据表名检索一组数据或记录。

  • DefaultView

    表的自定义视图,如过滤视图或光标位置。

  • HasErrors

    如果任何行有错误,则显示错误。

  • 区域设置 (Locale)

    用于比较字符串的本地信息。

  • MinimumCapacity

    表的初始大小。

  • ParentRelations

    与父表发生的任何关系。

  • PrimaryKey

    用于唯一标识行的键。

  • Rows

    行数作为集合。

  • TableName

    数据库表的名称。

DataTable 的一些公共方法如下所示:

  • AcceptChanges

    提交事务。

  • BeginInit

    DataTable 的初始化。

  • BeginLoadData

    关闭通知、索引维护和约束。

  • Clear

    清除 DataTable 中的所有记录。

  • 克隆

    将结构复制到另一个表(包括约束、关键字段、模式等)。

  • Compute

    根据表达式过滤数据。

  • 复制

    复制数据库结构和数据(不像 Clone)。

  • 处置

    从内存中释放(卸载)。

  • EndInit

    初始化结束时触发。

  • EndLoadData

    DataTable 加载数据结束时触发。

  • GetErrors

    获取包含错误的 DataRow 对象数组。

  • ImportRow

    导入记录。

  • LoadDataRow

    根据条件更新行。如果找不到匹配记录,则插入记录。

  • NewRow

    DataTable 中创建新行。

  • RejectChanges

    回滚更改。

  • Reset

    DataTable 重置到原始位置。

  • Select

    获取数据记录数组。

DataTable 相关的一些事件有 ColumnChangedColumnChangingRowChangedRowChangingRowDeletedRowDeleting 等。

注意System.Data 命名空间用于包含在您的项目中,它主要由构成 ADO.NET 架构的类组成。用于创建 DataSet 对象的程序集名称是 System.Data.dll 文件中的 System.Data

关于“SQLDataAdapter”类

SQLDataAdapter 类用于在 DataSet 中检索和更新数据库记录。它是 SQL Server 和 DataSet 之间的桥梁。

有两种方法用于添加或更新记录。它们是:

  • Add 方法将填充或刷新 DataSet 中的行或记录。
  • Update 方法用于更新 DataSet 中的记录。请注意,这将根据 SqlAdapter 状态调用相应的 SQL 语句,例如 INSERTUPDATEDELETE

以下代码行将帮助您了解 SqlDataAdapter 如何负责使用 SqlCommand 对象填充 DataSet

' fill a DataSet.
' A SqlCommand object is used to execute sql statements,
' which we already discussed the Article 1
Dim Mycmd As New SqlCommand(“SELECT * FROM dbo.Customer”, myConnection)
Dim mySqlDataAdapter As New SqlDataAdapter(Mycmd)
Dim mydsCustomer As New DataSet()
         
mySqlDataAdapter.Fill(mydsCustomer, "Customer")

关于 DataGrid 控件

DataGrid 控件从表中的数据源填充行。它用于检索和更新数据库记录。DataGrid 控件支持选择、编辑、删除、分页和排序。

DataGrid 中的不同列类型决定了控件中列的行为。一些列类型有 BoundColumnButtonColumnEditCommandColumnHyperLinkColumnTemplateColumn 等。

注意:System.Web.UI.WebControls 命名空间用于将此对象包含到您的应用程序中。用于创建 DataGrid 控件的程序集名称是 System.Web.dll 文件中的 System.Web

在 .NET 表单上使用 DataGrid 控件的步骤

DataGrid 控件允许您从表中的数据源中选择、排序和编辑项目。

  1. DataGrid 绑定到 DataSet

    首先,您需要将 DataSet 绑定到 DataGrid,然后将 Visible 属性设置为 True。如果您不将 Visible 属性设置为 TrueDataGrid 仍然会显示,但滚动条会丢失。

    ' Set the DataGrid caption, bind it to the DataSet, and then make it
    ' Visible            
    mydgCustomer.CaptionText = "Customer"
    ' Notice here that instead of using the DataSet table name, 
    ' "customers", the alternate syntax of table index is used.
    mydgCustomer.DataSource = mySqlDataAdapter.Tables(0)
    mydgCustomer.Visible = True

    请注意语法 mySqlDataAdapter.Tables(0),您也可以使用带有 DataSet 表名“Customer”的替代语法。

  2. 自定义格式化 DataGrid

    表格样式对象允许您自定义格式化 DataGrid 对象。用于自定义格式化 DataGrid 对象的对象名称是 DataGridTableStyle。它表示 System.Windows.Forms.DataGrid 控件在运行时绘制的表格。它是一个类文件,表示应用自定义格式来绘制网格。

    以下是 DataGridTableStyle 属性列表,可以设置这些属性来覆盖 System.Windows.Forms.DataGrid 控件属性。这样,它允许您进行自己的自定义格式化。

    • AllowSorting 属性允许您根据用户单击每个列标题进行排序,这将按升序或降序排序。当 AllowSorting 属性设置为 True 时,每个列标题中会出现一个三角形,指示排序方向。用户可以单击任何列标题以按该列排序网格。第二次单击列会更改排序方向。如果允许排序,则返回 True,否则返回 False。此属性的默认值为 True
    • AlternatingBackColor 允许您设置交替的行颜色(或获取或设置网格奇数行的背景颜色)。
      mydgCustomer.AlternatingBackColor = System.Drawing.Color.Red
    • BackColor 属性设置对象的背景颜色。
    • ColumnHeadersVisible 属性允许您在表单上的 DataGrid 控件中隐藏或显示列标题。
    • ForeColor 允许您设置 DataGrid 控件的前景颜色。
    • GridLineColor 允许您设置 DataGrid 线条颜色。
    • GridLineStyle 允许您设置 DataGrid 的样式。
      mydgCustomer.GridLineStyle = 
             System.Windows.Forms.DataGridLineStyle.None
      mydgCustomer.GridLineStyle = 
             System.Windows.Forms.DataGridLineStyle.Solid
    • HeaderBackColor 允许您设置或获取标题的背景颜色。
    • HeaderFont 允许您设置或获取 DataGrid 控件上的标题字体。
    • HeaderForeColor 设置列标题的前景颜色。
    • LinkColor 允许您设置网页链接文本的颜色。
    • PreferredColumnWidth 允许您设置 DataGrid 列宽。
    • PreferredRowHeight 允许您设置 DataGrid 行高。
    • ReadOnly 属性允许您将 DataGrid 设置为只读。无法进行编辑(更新、插入或删除)。
    • RowHeadersVisible 属性允许您获取或设置 DataGrid 控件上行标题的可见属性。

使用 DataSet 和 DataGrid 控件显示数据的步骤

您现在了解了 DataTableDataSet 对象、DataAdapter 类和 DataGrid 控件的基本功能。接下来,我将逐步解释如何在您的 .NET 应用程序中创建和使用这些对象、类或控件。

  1. 创建并打开数据库连接、数据库对象。

    如果您想了解更多关于创建数据库和表的信息,请参阅我之前的文章,其中描述了如何使用 WhidBey 或 .NET 环境创建和打开数据库连接。此外,之前的文章还解释了如果我们只安装了 MSDE,如何打开 SQL 数据库连接。为了解决这个问题,我们在 .NET Whidbey 中使用了 SQL 错误异常代码。

  2. DataGrid 控件添加到您的表单。

    将一个新的 DataGrid 控件添加到您的表单,并将其命名为 mydgCustomer

  3. 绑定到 DataGrid 以进行显示。

    在您的表单上添加 DataGrid 控件后,下一步是使用 DataAdapter 填充数据。以下例程从 Mydatabase 表中获取客户信息,将其放入一个 DataSet 中,该 DataSet 用于绑定到 DataGrid 以进行显示。

    If IsNothing(mydgCustomer.DataSource) Then
        Dim strMySQL As String = _
          "USE MyDatabase " & vbCrLf & _
          "SELECT * " & _
          "FROM myStoredProcedure"
        Try
            ' The SqlConnection class allows you to communicate
            ' with SQL Server and DataTable.
            Dim myConnection As New SqlConnection(myConnection) 
            ' A SqlCommand object is used to execute the SQL commands.
            Dim mycmd As New SqlCommand(strMySQL, myConnection) 
            Dim mySqlDataAdapter As New SqlDataAdapter(mycmd)
            Dim mydsCustomer As New DataSet() 
            ' The SqlDataAdapter is responsible for using
            ' a SqlCommand object to fill a DataSet. 
            mySqlDataAdapter.Fill(mydsCustomer, "Customer") 
            ' Set the DataGrid caption, bind it to the DataSet,
            ' and then make it Visible            
            mydgCustomer.CaptionText = "Customer" 
            ' Notice here that instead of using the DataSet table name, 
            ' "Customers", the alternate syntax of table index is used. 
            mydgCustomer.DataSource = mySqlDataAdapter.Tables(0) 
            ' Settings to the DataGrid Styles, which will call the procedure
            ' setMyDataGridTableStyleProperties and the parameter
            ' as DataGrid
            setMyDataGridTableStyleProperties(mydgCustomer)
            mydgCustomer.Visible = True
    
        Catch sqlExc As SqlException 
            MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _
                        MessageBoxButtons.OK, MessageBoxIcon.Error) 
        End Try 
    End If
  4. 更新 DataGrid 样式属性。

    过程 setMyDataGridTableStyleProperties 允许您设置 DataGrid 样式属性,将 DataGrid 作为对象参数传递。

    首先,我们需要使用 DataGridTableStyle 对象创建 DataGrid 样式,并可以应用样式属性,例如 AlternatingBackColorBackColorForeColorGridLineColorHeaderrBackColorHeaderFontHeaderForeColorLinkColorMapping 等。AddRange 方法功能允许您在 DataGrid 组件的特定范围内设置样式。

    Private Sub setMyDataGridTableStyleProperties (ByRef myDG as DataGrid)
    ' Use a table style object to apply custom formatting 
    ' to the  DataGrid.
    
        Dim mydgTableStyle As New DataGridTableStyle()
        Dim mygrdColStyle1, mygrdColStyle2, mygrdColStyle3, _
           mygrdColStyle4, mygrdColStyle5 As New   & _
           DataGridTextBoxColumn() 
        With mydgTableStyle
            .AlternatingBackColor = Color.LightCoral
            .BackColor = Color.LawnGreen
            .ForeColor = Color.LightGray
            .GridLineColor = Color.LightGreenrodYellow
            .GridLineStyle = System.Windows.Forms.DataGridLineStyle.
            .HeaderBackColor = Color. LightGray
            .HeaderFont = New Font("Courier", 10.0!, FontStyle.Bold)
            .HeaderForeColor = Color. LawnGreen
            .LinkColor = Color.Teal 
            ' Do not forget to set the MappingName property. 
            ' Without this, the DataGridTableStyle properties
            ' and any associated DataGridColumnStyle objects
            ' will have no effect. 
            .MappingName = "Customers" 
            .SelectionBackColor = Color. LawnGreen
            .SelectionForeColor = Color. LightGray
        End With 
        ' Use column style objects to apply formatting specific
        ' to each  column of customer table.
        With mygrdColStyle1
            .HeaderText = "ID#"
            .MappingName = "CustomerID"
            .Width = 50
        End With 
        With mygrdColStyle2
            .HeaderText = "Last Name"
            .MappingName = "NameLast"
            .Width = 140
        End With 
        With mygrdColStyle3
            .HeaderText = "Address"
            .MappingName = "Address1"
            .Width = 180
        End With 
        With mygrdColStyle4
            .HeaderText = "State"
            .MappingName = "State"
            .Width = 30
        End With 
        With mygrdColStyle5
            .HeaderText = "Phone"
            .MappingName = "Phone"
            .Width = 70
        End With
        ' Add the column style objects to the tables style's 
        ' column styles collection. If you fail to do this the column 
        '  styles will not apply.
        mydgTableStyle.GridColumnStyles.AddRange _
                        (New DataGridColumnStyle() _
                        { mygrdColStyle1, mygrdColStyle2, _
                        mygrdColStyle3, mygrdColStyle4, mygrdColStyle5})
        ' Add the table style object to the DataGrid's table styles 
        ' collection. Again, failure to add the style to the collection 
        ' will cause the style to not take effect.
    
        myDG.TableStyles.Add(mydgTableStyle)
    End Sub

要求

  • Microsoft Visual Studio.Whidbey Ver 8.0 或
  • Microsoft Visual Studio .NET Professional 或更高版本。
  • Windows 2000 或 Windows XP。

摘要

从本文中,我们了解了 DataSetDataTable 对象、DataAdapter 类的描述。此外,您对使用 DataAdapter 类中的 Fill 方法使用 DataGrid 有了一个简要的了解。它还解释了如何在 DataGrid 中使用样式。

如果您需要任何建议或帮助,请通过 benoyraj@yahoo.com 联系我。

© . All rights reserved.