我使用实体框架连接到数据库,并将汽车的品牌和型号放入列表框中,格式为:Make - Model。
当我从列表框中选择一个项目时,我想获取该对象的ID以在另一个查询中使用它,该查询将在文本块中显示该特定汽车(数据库中的行)的完整详细信息。
当我从列表框中选择一个项目时,它会在以下位置返回一个空值:
int id =(int)ltbxAvailableCars.SelectedValue;
在XAML中,我已指定:
Listbox SelectedValuePath =“ID”
这里有没有明显的错误,我只是没有看到?
提前谢谢。
public partial class MainWindow : Window
{
CarRentalDBEntities db = new CarRentalDBEntities();
public enum CarType { All, Small, Medium, Large }
public MainWindow()
{
InitializeComponent();
cbxCarType.ItemsSource = Enum.GetValues(typeof(CarType));
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
CarType type;
Enum.TryParse<CarType>(cbxCarType.SelectedValue.ToString(), out type);
string carType = type.ToString();
if (carType == "All")
{
ltbxAvailableCars.Items.Clear();
var cars = from c in db.Cars
select new
{
c.ID,
c.Make,
c.Model,
c.Size
};
foreach (var car in cars)
{
ltbxAvailableCars.Items.Add(car.Make + " - " + car.Model);
}
}
else
{
ltbxAvailableCars.Items.Clear();
var cars = from c in db.Cars
where c.Size == carType
select new
{
c.ID,
c.Make,
c.Model,
c.Size
};
foreach (var car in cars)
{
ltbxAvailableCars.Items.Add(car.Make + " - " + car.Model);
}
}
}
private void ltbxAvailableCars_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int id = (int)ltbxAvailableCars.SelectedValue;
CarRentalDBEntities db = new CarRentalDBEntities();
var query = from c in db.Cars
where c.ID == id
select new
{
c.ID,
c.Make,
c.Model,
c.Size
};
tblkSelectedCarDetails.Text = query.ToString();
}
}
答案 0 :(得分:1)
这是针对您的案例的方法。但是根据我的观点,你提到ObservableCollection
的数据绑定似乎更优雅,甚至更容易
创建用于在列表框项目中保留所需值的类
public class Car
{
public Int32 ID { get; set; }
public DateTime Make { get; set; }
public String Model { get; set; }
public override string ToString()
{
return String.Format("{0} - {1}", this.Make, this.Model);
}
}
ToString
将覆盖并返回您希望在列表框中显示的字符串
ListBox调用显示文本的项目.ToString()
方法
然后在LINQ查询中创建该类的实例并将它们添加到列表框
ltbxAvailableCars.Items.Clear();
var cars = from c in db.Cars
where c.Size == carType
select new Car
{
ID = c.ID,
Make = c.Make,
Model = c.Model
};
foreach (Car car in cars)
{
ltbxAvailableCars.Items.Add(car);
}
并在SelectionChanged
事件处理程序
private void ltbxAvailableCars_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Car temp = (Car)ltbxAvailableCars.SelectedItem;
Int32 id = temp.ID
CarRentalDBEntities db = new CarRentalDBEntities();
var query = from c in db.Cars
where c.ID == id
select new
{
c.ID,
c.Make,
c.Model,
c.Size
};
tblkSelectedCarDetails.Text = query.ToString();
}
答案 1 :(得分:0)
与您的情况相关,您可以尝试使用e.AddedItems
(传递给您的方法ltbxAvailableCars_SelectionChanged
的args)并从中提取值,如MSDN在线详细说明:https://msdn.microsoft.com/en-us/library/system.windows.controls.selectionchangedeventargs%28v=vs.110%29.aspx
希望这可能有所帮助。最好的问候,