将datagrid绑定到combobox WPF

时间:2018-11-07 04:05:57

标签: wpf vb.net

请帮助我! 在SQL Server中,我创建表temp:

CREATE TABLE temp(
user_temp nvarchar(5),
year_temp int)

表temp中的值:

user_temp        year_temp
   A                5
   B                6
   C                5

在窗口中,我创建了一个Datagrid和一个ComboBox,我写道:

Private Sub Windowtemp_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    Dim s as string="select * from temp"
    Dim cmd as new New SqlClient.SqlCommand(s, connect)
    Dim adaptertemp As New SqlClient.SqlDataAdapter

    adaptertemp.SelectCommand = cmd

    Dim tabletemp As New DataTable

    adaptertemp.Fill(tabletemp)
    datagridtemp.ItemsSource = tabletemp.DefaultView
    cmd.Dispose()
    adaptertemp.Dispose()
    tabletemp.Dispose()

    Dim i as interger

    for i= 10 to 20
        cbo.Items.Add(i)
    Next
End Sub

在数据网格选择中已更改:

Private Sub gridtemp_SelectionChanged(sender As Object, e As SelectionChangeEventArgs) Handles gridtemp.SelectionChanged
    cbo.Text = gridtemp.SelectedItem.row(1).ToString
End Sub

但是组合框未显示gridtemp的值。我应该怎么做才能做到这一点?预先感谢!

1 个答案:

答案 0 :(得分:0)

SelectedItem返回一个DataRowView。试试这个:

Private Sub gridtemp_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles gridtemp.SelectionChanged
    If Not gridtemp.SelectedItem Is Nothing Then
        Dim selectedItem = CType(gridtemp.SelectedItem, DataRowView)
        cbo.SelectedItem = Convert.ToInt32(selectedItem(1))
    End If
End Sub