Linq-to-SQL组合框绑定

时间:2015-02-06 23:54:51

标签: c# wpf linq linq-to-sql combobox

我正在尝试使用combobox items填充list of objectslinq to sql的方式填写select new,以Tax方式提供dt = new LilkaDataContext(); var taxes = from p in dt.Taxes select new { Id = p.Id, Name = p.Name, Percentage = p.Percentage, Note = p.Note }; cb.ItemsSource = taxes;

请注意,<ComboBox Name="CbSettingsTax" Grid.Column="2" SelectedValue="Id" DisplayMemberPath="Name" > </ComboBox> 参数与选择新参数完全相同。

int selectedTax = ((Tax)CbProductTax.SelectedItem).Id;

XAML

select new

现在我需要解析该值并检索我填充的组合框中选择的Tax Id。

Tax.Id

由于select new创建新对象而导致错误。我想知道是否有任何方法可以解析最后一步以获得4[System.Int32,System.String,System.Nullable或更好地填充而不用dt = new LilkaDataContext(); var taxes = from p in dt.Taxes select p; cb.ItemsSource = taxes; /创建新对象。

  

其他信息:无法将类型为'&lt;&gt; f__AnonymousType1 {{1}} 1 [System.Decimal],System.String]'的对象转换为'lilka.Tax'。

编辑:

{{1}}

使用此查询我无法从GUI中的Combobox项目列表中选择项目。它只是没有显示为选定项目。

2 个答案:

答案 0 :(得分:2)

直接从查询中放入数据,而不是创建新对象:

dt = new LilkaDataContext();
var taxes = from p in dt.Taxes select p;
cb.ItemsSource = taxes.ToList(); 

答案 1 :(得分:1)

首先让我们谈谈您的ComboBox:您应该使用SelectedValuePath属性而不是SelectedValue。所以:

<ComboBox Name="CbSettingsTax" Grid.Column="2" 
                              SelectedValuePath="Id"
                              DisplayMemberPath="Name" />

以这种方式,您的代码CbSettingsTax.SelectedValue将返回所选Tax对象的Id值,而CbSettingsTax.SelectedItem将返回整个所选对象。

关于Linq-To-Sql,我发现你正在使用&#34;查询语法&#34;。我个人更喜欢&#34;方法语法&#34;。当你写

var taxes = from p in dt.Taxes select new
{
      Id = p.Id, 
      Name = p.Name,
      Percentage = p.Percentage,
      Note = p.Note
};

由于您使用的是new关键字,编译器会为您创建一个Anonimous Type,它有4个属性,分别是Id,Name,Percentage和Note。然后LINQ在新的类中复制Tax属性值。

然而此匿名类型与Tax类型不同。因此,您无法将其强制转换为Tax。事实上,税收是这种匿名类型的集合。它不是Tax对象的集合。

之前我告诉过你我更喜欢LINQ&#34;方法语法&#34;,因为每个LINQ方法都返回一个通用的IEnumerable。 当然,您可以使用查询语法获得相同的结果,但很容易出错。

如果您使用(例如):

dt = new LilkaDataContext();
cb.ItemsSource = dt.Taxes.Where(tax => tax.Name.Contains("VAT"));

你的组合框将有一个Tax对象集合作为ItemsSource。

现在你只需要选择你的方法。您可以使用&#34;方法语法&#34;然后从组合框中删除SelectedValuePath属性。另一方面,您可以继续使用&#34;查询语法&#34;,但在这种情况下,您必须使用SelectedValuePath属性,您的代码将是:

int id = (int)CbProductTax.SelectedValue;

我希望它可以帮到你。