'通用样式化Datagird
'Power by:landlordh
Private Sub style()
Try
'列名,有多少写多少个
Dim strHeaders() As String = {"编号", "添加时间", "代码主题", "代码内容"}
'列宽,为0隐藏
Dim iWidths() As Integer = {0, 70, 130, 0}
DataGrid1.DataSource = DataSet1.Tables("codes")
DataSet1.Tables("codes").DefaultView.AllowNew = False
DataSet1.Tables("codes").DefaultView.AllowEdit = False
Dim i As Integer
Dim ts As New DataGridTableStyle
ts.MappingName = DataSet1.Tables("codes").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 DataSet1.Tables("codes").Columns.Count - 1
Dim ac As New DataGridTextBoxColumn
AddHandler ac.TextBox.Enter, AddressOf TextBoxEnterHandler
ac.HeaderText = strHeaders(i)
ac.MappingName = DataSet1.Tables("codes").Columns(i).ColumnName
ac.TextBox.Width = iWidths(i)
ts.PreferredColumnWidth = ac.TextBox.Width
ts.GridColumnStyles.Add(ac)
'哪列,i=第几列数-1
If i = 1 Or i = 2 Then
'你要的效果
'ac.Format = "yyyy-mm-dd hh:mm:ss"
'ac.ReadOnly = True
'ac.NullText = ""
ac.Alignment = HorizontalAlignment.Center
End If
Next
DataGrid1.TableStyles.Clear()
DataGrid1.TableStyles.Add(ts)
Catch ex As Exception
MessageBox.Show("格式化网格出错了")
End Try
End Sub