[英]How to Populate ListBox with Linq to Sql C#
我有一個問題,即如何在沒有 db 列和大括號的情況下使用來自數據庫的數據填充 ListBox,這是我的代碼:
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;
如果你試圖返回一個新對象,你必須告訴它屬性為
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();
嘗試添加這個
", " + 語句之間
a.PlayerOne+ ", " +a.PlayerTwo+ ", " + a.Date+ ", " + a.ResultOne+ ", " + a.ResultTwo
它會工作
請看這里的答案: 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; }
}
看起來像這樣:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.