wpf 如何使用Linq to Sql C#填充列表框

anhgbhbe  于 2023-10-22  发布在  C#
关注(0)|答案(4)|浏览(152)

我有一个问题,如何填充一个ListBox与数据库的数据没有列的db和花括号这里是我的代码:

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;

结果是:

我只想要这些列中的数据。

6kkfgxo0

6kkfgxo01#

如果你试图返回一个新的对象,你必须告诉它的属性,

select new {PlayerOne = a.PlayerOne
            //More Properties Here
           }

根据你的例子,

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
        {
            PlayerOne = a.PlayerOne,
            PlayerTwo = a.PlayerTwo,
            Date = a.Date,
            ResultOne = a.ResultOne,
            ResultTwo = a.ResultTwo
        }).ToList();

    listBox.ItemsSource = history;

这将返回一个没有类型的新对象列表,但属性将在那里

编辑:如果您想要表中的所有数据,其中PlayerOne和PlayerTwo等于一个文本框值,请执行以下操作

var history = db.ResultsHistories.Where(x => x.PlayerTwo == comboBox.Text || x.PlayerOne == comboBox.Text).Select(x => x).ToList();
nc1teljy

nc1teljy2#

尝试添加此内容

  • “,“+语句之间

a.PlayerOne+“、“+a.PlayerTwo+“、“+ a.Date+“、“+ a.ResultOne+“、“+ a.ResultTwo

它会工作

e0uiprwp

e0uiprwp3#

<ListBox x:Name="listBx_ShowPersons">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding firstName}"/>
                            <TextBlock Text=", "/>
                            <TextBlock Text="{Binding lastName}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>                    
            </ListBox>

listBx_ShowPersons.ItemsSource = from p in _dataContext.Persons select new { p.firstName, p.lastName };

6uxekuva

6uxekuva4#

请在这里看看答案:Multicolumn ListBox in WPF
您也可以使用DataGrid来实现此目的。XAML代码是:

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

后面有一个非常简单的代码:

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; }
}

它看起来像这样:

相关问题