通用样式化Datagird

发表于:2007-06-30来源:作者:点击数: 标签:
很多初学 VB .NET的新手,差不多都是对许多小功能不能实现而苦恼, 以下我个人在论坛中遇到的许多问题的综合的通用代码,供初学者研究学习: @#通用样式化Datagird @#Power by:landlordh @#调用: @# strHeaders() 里面改为自已需要的列名 @# iWidths() 里面改
很多初学VB.NET的新手,差不多都是对许多小功能不能实现而苦恼,
以下我个人在论坛中遇到的许多问题的综合的通用代码,供初学者研究学习:

@#通用样式化Datagird
@#Power by:landlordh
@#调用:
@# strHeaders() 里面改为自已需要的列名
@# iWidths() 里面改为相对应的列宽
@# inputnum 在样式化之前赋值
@# style(DataGrid1, DataSet1.Tables("tabname"))
@#
@#=================================================================

@#列名,字段对应名
Public strHeaders() As String = {"编号", "时间", "主题", "内容"}
@#列宽,为0隐藏(优先级低于inputnum),对应的列宽
Public iWidths() As Integer = {0, 70, 130, 0}
@#显示几列,为空则显示所有,为0则隐藏所有
Public inputnum As String

Public Sub style(ByVal datagridname As DataGrid, ByVal dataname As DataTable)
Try
datagridname.DataSource = dataname
@#显示新增
@#dataname.DefaultView.AllowNew = False
@#在datagrid中直接编辑
@#dataname.DefaultView.AllowEdit = False
Dim i As Integer
@#处理显示前几列的参数
If Trim(inputnum) <> "" Then
Dim num As Integer
Try
num = CInt(Trim(inputnum))
Try
For i = 0 To iWidths.Length - 1
If i >= inputnum Then
iWidths(i) = 0
End If
Next
Catch ex As Exception
End Try
Catch ex As Exception
MsgBox("你输入的字符不符合要求")
End Try
End If
Dim ts As New DataGridTableStyle
ts.MappingName = dataname.TableName
ts.AlternatingBackColor = System.Drawing.Color.PapayaWhip
ts.BackColor = System.Drawing.Color.WhiteSmoke
ts.SelectionBackColor = System.Drawing.Color.LightSteelBlue
ts.SelectionForeColor = Color.Black
ts.RowHeaderWidth = 10
ts.PreferredRowHeight = 20
For i = 0 To dataname.Columns.Count - 1
Dim ac As New DataGridTextBoxColumn
@#处理点击行
@#AddHandler ac.TextBox.Enter, AddressOf TextBoxEnterHandler
ac.HeaderText = strHeaders(i)
ac.MappingName = dataname.Columns(i).ColumnName
ac.TextBox.Width = iWidths(i)
ts.PreferredColumnWidth = ac.TextBox.Width
@#哪列,i=第几列数-1
If i = 1 Then
ac.Format = "yyyy-mm-dd hh:mm:ss"
@#ac.ReadOnly = True
@#ac.NullText = ""
ac.Alignment = HorizontalAlignment.Center
End If
If i = 1 Or i = 2 Then
@#ac.ReadOnly = True
@#ac.NullText = ""
ac.Alignment = HorizontalAlignment.Center
End If
ts.GridColumnStyles.Add(ac)
Next
datagridname.TableStyles.Clear()
datagridname.TableStyles.Add(ts)
Catch ex As Exception
MessageBox.Show("格式化网格出错了")
End Try
End Sub

结束

原文转自:http://www.ltesting.net