将数据表应用于wpf中的组合框

时间:2016-10-04 11:04:50

标签: c# wpf combobox

请帮我纠正此问题,我收到错误(NullReferenceException

  

类型' System.NullReferenceException'的例外情况发生在HMCS.exe中,但未在用户代码中处理'

CodeBehind -

dt = oBALSubLocation.SelectLocation(oBOSubLocation);
cmbSubLocation.ItemsSource = dt;

用户界面 -

<ComboBox x:Name="cmbSubLocation" HorizontalAlignment="Left" Margin="256,41,0,-6" VerticalAlignment="Top" Width="108" Height="26" FontSize="13" />

1 个答案:

答案 0 :(得分:0)

名称是您要显示的列名称:

的Xaml:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="MainWindow">
<Grid>

    <ComboBox x:Name="ComboBox" HorizontalAlignment="Left" Margin="256,41,0,-6"
        VerticalAlignment="Top" Width="108" Height="26" FontSize="13" >
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

</Grid>

代码隐藏:

 public partial class MainWindow : Window
 {
    public MainWindow()
    {
        InitializeComponent();

        DataTable dt = GetTable();
        ComboBox.ItemsSource = dt.AsDataView();
    }

    static DataTable GetTable()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Name", typeof(string));
        table.Rows.Add("Test1");
        table.Rows.Add("Test2");
        table.Rows.Add("Test3");
        return table;
    }
 }