Search code examples
c#wpflinq-to-sql

How to Populate ListBox with Linq to Sql C#


I have a question of how to populate a ListBox with data from Database without the columns of db and curly brackets here is my code:

var db = new DataClasses1DataContext();
        var history =( from a in db.ResultsHistories
            where
                a.PlayerOne == _playerOne && a.PlayerTwo == comboBox.Text ||
                a.PlayerTwo == _playerOne && a.PlayerOne == comboBox.Text
            select new
            {
                a.PlayerOne,
                a.PlayerTwo,
                a.Date,
                a.ResultOne,
                a.ResultTwo
            }).ToList();

        listBox.ItemsSource = history;

And the result: enter image description here I want only Data in these columns.


Solution

  • Please have a look at the answer here: Multicolumn ListBox in WPF

    You can also use a DataGrid for this purpose. The XAML code for that would be:

    <DataGrid x:Name="NamesDataGrid"></DataGrid>
    

    and a very simple code behind:

    public partial class MainWindow : Window
    {
        private readonly List<Name> _nameList = new List<Name>
        {
            new Name("Eric","Clapton"),
            new Name("Mark", "Knopfler")
        };
        public MainWindow()
        {
            InitializeComponent();
            NamesDataGrid.ItemsSource = _nameList;
        }
    }
    
    internal class Name
    {
        public Name(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    Which will look like this:

    enter image description here