日期:2012-05-04  浏览次数:20532 次

一个通用的DataGridTableStyle的做法



哈,这两天都喜欢写“通用”的东西。

这个类,可以实现自适应列宽、只读、时分显示、事件、任意位置加列、单击单元格背景色设置等等,操作简便。只是时间关系(明天要出去一趟),今天没办法完善。仅供参考,你可以加入别的东西。以下只列代码了,不清楚的自己试用查资料就行了。



Public Class TableStyle



Private m_DataGridTableStyle As DataGridTableStyle

Private m_DataGrid As DataGrid

Private m_DataTable As DataTable

'//添加事件处理,在此只考虑DataGridTextBoxColumn双击事件

Public Delegate Sub ClickEventHandler(ByVal sender As Object, ByVal e As System.EventArgs)

Public Event GridTextBoxDoubleClickEvent As ClickEventHandler

Public Sub GridTextBox_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)

RaiseEvent GridTextBoxDoubleClickEvent(sender, e)

End Sub

'//设置DataGrid

Public Property [DataGrid]() As DataGrid

Get

Return m_DataGrid

End Get

Set(ByVal Value As DataGrid)

m_DataGrid = Value

End Set

End Property

'//返回模板

Public ReadOnly Property [DataGridTableStyle]() As DataGridTableStyle

Get

Return m_DataGridTableStyle

End Get

End Property

'//初始化

Public Sub Initialize()

'//判断mDataGrid数据源类型

'//如果绑定的是DataSet或DataViewManager或没有绑定任何数据源,则退出,

If TypeOf m_DataGrid.DataSource Is System.Data.DataSet OrElse _

TypeOf m_DataGrid.DataSource Is System.Data.DataViewManager OrElse _

m_DataGrid.DataSource Is Nothing Then Exit Sub



'//以下分别考虑两种数据源,一是DataView,一是DataTable

If TypeOf m_DataGrid.DataSource Is System.Data.DataView Then

m_DataTable = CType(m_DataGrid.DataSource, DataView).Table

Else

m_DataTable = CType(m_DataGrid.DataSource, DataTable)

End If



m_DataGridTableStyle = New DataGridTableStyle

m_DataGridTableStyle.MappingName = m_DataTable.TableName

'//加ColumnStyle

Dim mDataColumn As DataColumn

Dim mColumnStyle As DataGridColumnStyle

For Each mDataColumn In m_DataTable.Columns



Select Case mDataColumn.DataType.Name

Case "Boolean"

mColumnStyle = New DataGridBoolColumn

Case Else

mColumnStyle = New DataGridTextBoxColumn

AddHandler CType(mColumnStyle, DataGridTextBoxColumn).TextBox.DoubleClick, AddressOf GridTextBox_DoubleClick

End Select



'//绑定到DataTable的Column

With mColumnStyle

.MappingName = mDataColumn.ColumnName

.HeaderText = mDataColumn.ColumnName

End With



'//加入到DataGridTableStyle

m_DataGridTableStyle.GridColumnStyles.Add(mColumnStyle)

Next



'//将DataGridTableStyle绑定到DataGrid

m_DataGrid.TableStyles.Clear()

m_DataGrid.TableStyles.Add(m_DataGridTableStyle)

End Sub

'//自适应宽度

Public Sub AutoExtend()

If m_DataGridTableStyle Is Nothing Then Exit Sub

'取各字段的最大字节数,包括字段名和值

Dim mRow As DataRow

Dim mColumn As DataColumn

For Each mColumn In m_DataTable.Columns

m_DataGridTableStyle.GridColumnStyles(mColumn.ColumnName).Width = GetColumnMaxWidth(0, mColumn.ColumnName)

Next



For Each mRow In