设置DataGrid表格控件的列显示样式,例如设置列宽,表头等

类别:.NET开发 点击:0 评论:0 推荐:
设置DataGrid表格控件的列显示样式,例如设置列宽,表头等。
代码示例:
假设使用数据库为SQL Server,数据库名为 Test,表 t_operator(operid,name)
本例中的DataGrid表格控件名称为DG

Imports System.Data.SqlClient
…………

Private Sub SetDataGrid()
    Dim Tstyle As New DataGridTableStyle
        Dim DCstyle As DataGridColumnStyle

        DCstyle = New DataGridTextBoxColumn '创建一个新列
        With DCstyle
            .MappingName = "operid" ' 设置字段映射关系
            .HeaderText = "编号" '设置表头显示字符
            .Width = 75 '设置列宽
                    '如果要设置数值或日期的显示格可以设置Format属性,例如: .Format = "¥0.00"
        End With

        Tstyle.GridColumnStyles.Add(DCstyle)
        DCstyle.Dispose()
        DCstyle = New DataGridTextBoxColumn

        With DCstyle
            .MappingName = "name"
            .HeaderText = "姓名"
            .Width = 75
        End With
        Tstyle.GridColumnStyles.Add(DCstyle)
        DCstyle.Dispose()
       
        Tstyle.GridColumnStyles.Add(DCstyle)
        Tstyle.MappingName = "t_operator" '设置映射表名
        Tstyle.HeaderBackColor = Me.BackColor
        DG.TableStyles.Add(Tstyle)
        DCstyle.Dispose()
        Tstyle.Dispose()
end Sub
'在窗体启动时,调用SetDataGrid()函数来设置DataGrid表格控件的显示样式。调用RetData()函数来返回数据
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    SetDataGrid()
    RetData()
end sub

'在RetData()函数里,假设SQL服务器名为Yong,用户名为sa,密码为123456
Private Sub RetData()
        Dim Cn As New SqlConnection("server=yong;database=Test;uid=sa;pwd=123456;")
        Dim Cmd As SqlCommand
        Dim DA As SqlDataAdapter
        Dim DSet As DataSet

        Try
            Cn.Open()
            Cmd = New SqlCommand
            Cmd.CommandText = "select operid,name from dbo.t_operator"
            Cmd.CommandType = CommandType.Text
            Cmd.Connection = Cn
            DA = New SqlDataAdapter(Cmd)
            DSet = New DataSet

            DA.Fill(DSet)
            DSet.Tables(0).TableName = "t_operator" '设置表名,与SetDataGrid()函数里的映射表名是一致的
            DG.DataSource = DSet.Tables(0)
            DSet.Dispose()
            DA.Dispose()
            Cmd.Dispose()
            Cn.Close()
        Catch ex As Exception
            MsgBox("连接数据库出错,原因如下:" & vbCrLf & ex.ToString, MsgBoxStyle.Critical)
        End Try
        Cn.Dispose()
End Sub

本文地址:http://com.8s8s.com/it/it42111.htm