Add combobox to datagrid that is linked to a datab

2019-07-17 05:36发布

问题:

My program is a WPF application written in VB.net. I accept answers geared toward C# as well, as I should be able to understand and/or convert.

I have a dataTable that I fill with data from my MySQL database via MySqlDataAdapter.

My dataGrid currently has AutoGenerateColumns="TRUE".

I load my dataTable data into my dataGrid by DataGrid1.ItemsSource = MyDataTable.DefaultView

In my table I have a column labeled "callType" that I would like to have be a comboBox (DataGridComboBoxColumn)

I have tried a variety of things that can be described as shots in the dark that are missing.

Would someone be able to nudge me in the right direction or show me some code on how to make a comboBox column in a dataGrid that is linked with the data of that dataGrid?

回答1:

Check How to: Customize Auto-Generated Columns in the DataGrid Control? . It says :

You can handle the AutoGeneratingColumn event to modify, replace, or cancel a column that is being generated. The AutoGeneratingColumn event occurs one time for each public, non-static property in the bound data type when the ItemsSource property is changed and the AutoGenerateColumns property is true.

Xaml :

<DataGrid AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"  />

Code :

Private Sub DataGrid_AutoGeneratingColumn(sender As System.Object, e As System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs)

        If e.PropertyName = "callType" Then

            Dim combo As New DataGridComboBoxColumn

            combo.ItemsSource = MyItemsSource
            combo.DisplayMemberPath = "TypeName" 
            combo.SelectedValuePath = "TypeID"

            Dim comboBinding As New Binding("callType")
            combo.SelectedValueBinding = comboBinding

            e.Column = combo

        End If

    End Sub