更改每个Itemsource .net填充的Datagrid的ColumnWidth

时间:2015-09-03 23:06:52

标签: wpf vb.net datagrid

我有一个填充了Datatable:

的Datagrid
Dim dataTable as new Datatable
Dim dataGrid as new DataGrid

然后我用数据填充Datatable并将其显示在Datagrid中。

dataGrid.ItemsSource = dataTable.DefaultView

万事如意。

但现在我想改变一些列的宽度,如:

datagrid.columns(0).Width = 100

- >错误:索引超出绑定异常。 - > Datagrid中没有列。

但我可以看到他们是专栏。当我设置ItemsSource时,它不会自动添加列?!

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以使用DataGrid.AutoGeneratingColumn事件修改列:

'Access and update columns during autogeneration 
Private Sub DG1_AutoGeneratingColumn(ByVal sender As Object, ByVal e As DataGridAutoGeneratingColumnEventArgs)
    Dim headername As String = e.Column.Header.ToString()
    'Cancel the column you don't want to generate 
    If headername = "IDontWantThisColumn" Then
        e.Cancel = True 
    End If 

    'update column details when generating 
    If headername = "MyFirstColumn" Then
        e.Column.Width = 100 
    ElseIf headername = "MySecondColumn" Then
        e.Column.Width = 120 
    End If 
End Sub