简体   繁体   中英

how do i display a DataTable in a wpf window c#?

I can't seem to find a clear solution for this here or google.

i basically have a DataTable that i added rows with data according to my needs, and i want to display it as a table in a wpf Window.

Any ideas how? Thanks in advance.

i tried this, but i got this exception: " System.NullReferenceException: 'Object reference not set to an instance of an object.' ListViewData was null. "

this is the method,and inside, the creation of the DataTable:

private void ShowAllPlayersbutton_Click(object sender, RoutedEventArgs e)
    {
        AllPlayersTable = new DataTable("test");
        AllPlayersTable.Columns.Add("Played games",typeof(int));
        AllPlayersTable.Columns.Add("Wins", typeof(int));
        AllPlayersTable.Columns.Add("Losses", typeof(int));
        AllPlayersTable.Columns.Add("Ties", typeof(int));
        AllPlayersTable.Columns.Add("Wins precentage",typeof(int));

        MsServiceClient proxy = new MsServiceClient(new InstanceContext(Callback));
        UserD[] usersArr = proxy.GetAllUsers();

        foreach(UserD uD in usersArr)
        {
            AllPlayersTable.Rows.Add(uD.PlayedGames, uD.Wins, uD.Losts, uD.Ties, uD.VictoryPercent);
        }

        DisplayUsersWindow displayWindow = new DisplayUsersWindow(AllPlayersTable);
        displayWindow.Show();

    }

this is the window's:

    public partial class DisplayUsersWindow : Window
{
    public DisplayUsersWindow()
    {
        InitializeComponent();
    }

    public DataTable Datas { get; set; }
    public DisplayUsersWindow(DataTable dataTable)
    {
        Datas = dataTable;
        ListViewData.ItemsSource = Datas.DefaultView;//<<<< exception happens here

    }

}

}

The NullReferenceException occurs because you didn't initialize your window in the constructor that is taking the DataTable, meaning ListViewData is not set to an object. To fix it, just add a call to InitializeComponent() :

public DisplayUsersWindow(DataTable dataTable)
{
    InitializeComponent();
    Datas = dataTable;
    ListViewData.ItemsSource = Datas.DefaultView;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM